qemu_driver.c 473.7 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
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
41
#include <stdio.h>
42
#include <sys/wait.h>
43
#include <sys/ioctl.h>
44
#include <sys/un.h>
45
#include <byteswap.h>
D
Daniel P. Berrange 已提交
46

47

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

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

97 98
#define VIR_FROM_THIS VIR_FROM_QEMU

99 100
#define QEMU_DRIVER_NAME "QEMU"

101 102
#define QEMU_NB_MEM_PARAM  3

103 104
#define QEMU_NB_BLOCK_IO_TUNE_PARAM  6

105 106
#define QEMU_NB_NUMA_PARAM 2

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

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

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

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

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

133
#define QEMU_NB_BLKIO_PARAM  2
134

135 136
#define QEMU_NB_BANDWIDTH_PARAM 6

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

139
static int qemuShutdown(void);
140

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

146
static int qemuDomainGetMaxVcpus(virDomainPtr dom);
147

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


152
virQEMUDriverPtr qemu_driver = NULL;
153 154


155 156 157 158 159 160 161 162 163 164 165 166 167 168
static void
qemuVMDriverLock(void) {
    qemuDriverLock(qemu_driver);
};


static void
qemuVMDriverUnlock(void) {
    qemuDriverUnlock(qemu_driver);
};


static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
169
                    virDomainObjListIterator iter, void *data)
170
{
171
    return virDomainObjListForEach(qemu_driver->domains, iter, data);
172 173 174 175 176 177 178 179 180 181
}

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


182
struct qemuAutostartData {
183
    virQEMUDriverPtr driver;
184 185
    virConnectPtr conn;
};
186

187 188 189 190 191 192 193 194 195 196 197 198
/**
 * qemuDomObjFromDomainDriver:
 * @domain: Domain pointer that has to be looked up
 * @drv: Pointer to virQEMUDriverPtr to return the driver object
 *
 * This function looks up @domain in the domain list and returns the
 * appropriate virDomainObjPtr. On successful lookup, both driver and domain
 * object are returned locked.
 *
 * Returns the domain object if it's found and the driver. Both are locked.
 * In case of failure NULL is returned and the driver isn't locked.
 */
199
static virDomainObjPtr
200
qemuDomObjFromDomainDriver(virDomainPtr domain, virQEMUDriverPtr *drv)
201
{
202
    virQEMUDriverPtr driver = domain->conn->privateData;
203 204 205 206
    virDomainObjPtr vm;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    qemuDriverLock(driver);
207
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
208 209 210 211
    if (!vm) {
        virUUIDFormat(domain->uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
212 213 214
        qemuDriverUnlock(driver);
        *drv = NULL;
        return NULL;
215 216
    }

217
    *drv = driver;
218 219 220
    return vm;
}

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
/**
 * qemuDomObjFromDomain:
 * @domain: Domain pointer that has to be looked up
 *
 * This function looks up @domain and returns the appropriate
 * virDomainObjPtr. The driver is unlocked after the call.
 *
 * Returns the domain object which is locked on success, NULL
 * otherwise. The driver remains unlocked after the call.
 */
static virDomainObjPtr
qemuDomObjFromDomain(virDomainPtr domain)
{
    virDomainObjPtr vm;
    virQEMUDriverPtr driver;

    if (!(vm = qemuDomObjFromDomainDriver(domain, &driver)))
        return NULL;

    qemuDriverUnlock(driver);

    return vm;
}
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

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

279 280
static int
qemuAutostartDomain(virDomainObjPtr vm,
281
                    void *opaque)
282 283
{
    struct qemuAutostartData *data = opaque;
284
    virErrorPtr err;
285
    int flags = 0;
286
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(data->driver);
287
    int ret = -1;
288

289
    if (cfg->autoStartBypassCache)
290
        flags |= VIR_DOMAIN_START_BYPASS_CACHE;
291

292
    virObjectLock(vm);
293
    virResetLastError();
294 295 296 297 298 299 300 301 302 303 304 305
    if (vm->autostart &&
        !virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJobWithDriver(data->driver, vm,
                                            QEMU_JOB_MODIFY) < 0) {
            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) {
306
            err = virGetLastError();
307
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
308
                      vm->def->name,
309
                      err ? err->message : _("unknown error"));
310
        }
311

312
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
313
            vm = NULL;
314
    }
315

316
    ret = 0;
317
cleanup:
318
    if (vm)
319
        virObjectUnlock(vm);
320
    virObjectUnref(cfg);
321
    return ret;
322 323
}

324

325
static void
326
qemuAutostartDomains(virQEMUDriverPtr driver)
327
{
328
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
329 330 331 332 333
    /* 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
     */
334
    virConnectPtr conn = virConnectOpen(cfg->uri);
335
    /* Ignoring NULL conn which is mostly harmless here */
336
    struct qemuAutostartData data = { driver, conn };
337

338
    qemuDriverLock(driver);
339
    virDomainObjListForEach(driver->domains, qemuAutostartDomain, &data);
340
    qemuDriverUnlock(driver);
341

342 343
    if (conn)
        virConnectClose(conn);
344
    virObjectUnref(cfg);
345 346
}

347
static int
348
qemuSecurityInit(virQEMUDriverPtr driver)
349
{
350
    char **names;
351 352
    virSecurityManagerPtr mgr = NULL;
    virSecurityManagerPtr stack = NULL;
353
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
354

355 356 357
    if (cfg->securityDriverNames &&
        cfg->securityDriverNames[0]) {
        names = cfg->securityDriverNames;
358
        while (names && *names) {
359 360
            if (!(mgr = virSecurityManagerNew(*names,
                                              QEMU_DRIVER_NAME,
361 362 363
                                              cfg->allowDiskFormatProbing,
                                              cfg->securityDefaultConfined,
                                              cfg->securityRequireConfined)))
364
                goto error;
365 366 367 368 369 370 371 372
            if (!stack) {
                if (!(stack = virSecurityManagerNewStack(mgr)))
                    goto error;
            } else {
                if (virSecurityManagerStackAddNested(stack, mgr) < 0)
                    goto error;
            }
            mgr = NULL;
373 374
            names++;
        }
375 376 377
    } else {
        if (!(mgr = virSecurityManagerNew(NULL,
                                          QEMU_DRIVER_NAME,
378 379 380
                                          cfg->allowDiskFormatProbing,
                                          cfg->securityDefaultConfined,
                                          cfg->securityRequireConfined)))
381
            goto error;
382
        if (!(stack = virSecurityManagerNewStack(mgr)))
383
            goto error;
384 385
        mgr = NULL;
    }
386

387
    if (cfg->privileged) {
388
        if (!(mgr = virSecurityManagerNewDAC(QEMU_DRIVER_NAME,
389 390 391 392 393 394
                                             cfg->user,
                                             cfg->group,
                                             cfg->allowDiskFormatProbing,
                                             cfg->securityDefaultConfined,
                                             cfg->securityRequireConfined,
                                             cfg->dynamicOwnership)))
395 396 397 398 399 400 401 402 403
            goto error;
        if (!stack) {
            if (!(stack = virSecurityManagerNewStack(mgr)))
                goto error;
        } else {
            if (virSecurityManagerStackAddNested(stack, mgr) < 0)
                goto error;
        }
        mgr = NULL;
404
    }
D
Daniel Veillard 已提交
405

406
    driver->securityManager = stack;
407
    virObjectUnref(cfg);
408
    return 0;
409

410
error:
411
    VIR_ERROR(_("Failed to initialize security drivers"));
412
    virSecurityManagerFree(stack);
413
    virSecurityManagerFree(mgr);
414
    virObjectUnref(cfg);
415 416
    return -1;
}
417

418

419
static virCapsPtr
420
qemuCreateCapabilities(virQEMUDriverPtr driver)
421
{
422
    size_t i;
423
    virCapsPtr caps;
424 425 426
    virSecurityManagerPtr *sec_managers = NULL;
    /* Security driver data */
    const char *doi, *model;
427
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
428

429
    /* Basic host arch / guest machine capabilities */
430
    if (!(caps = qemuCapsInit(driver->capsCache))) {
431
        virReportOOMError();
432
        virObjectUnref(cfg);
433
        return NULL;
434 435
    }

436
    if (cfg->allowDiskFormatProbing) {
437
        caps->defaultDiskDriverName = NULL;
438
        caps->defaultDiskDriverType = VIR_STORAGE_FILE_AUTO;
439 440
    } else {
        caps->defaultDiskDriverName = "qemu";
441
        caps->defaultDiskDriverType = VIR_STORAGE_FILE_RAW;
442 443
    }

444 445
    qemuDomainSetPrivateDataHooks(caps);
    qemuDomainSetNamespaceHooks(caps);
446

447
    if (virGetHostUUID(caps->host.host_uuid)) {
448 449
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot get the host uuid"));
450
        goto err_exit;
451
    }
452

453 454 455 456 457
    /* access sec drivers and create a sec model for each one */
    sec_managers = virSecurityManagerGetNested(driver->securityManager);
    if (sec_managers == NULL) {
        goto err_exit;
    }
458

459 460 461 462
    /* calculate length */
    for (i = 0; sec_managers[i]; i++)
        ;
    caps->host.nsecModels = i;
463

464
    if (VIR_ALLOC_N(caps->host.secModels, caps->host.nsecModels) < 0)
465 466
        goto no_memory;

467 468 469 470
    for (i = 0; sec_managers[i]; i++) {
        doi = virSecurityManagerGetDOI(sec_managers[i]);
        model = virSecurityManagerGetModel(sec_managers[i]);
        if (!(caps->host.secModels[i].model = strdup(model)))
471
            goto no_memory;
472
        if (!(caps->host.secModels[i].doi = strdup(doi)))
473
            goto no_memory;
474 475
        VIR_DEBUG("Initialized caps for security driver \"%s\" with "
                  "DOI \"%s\"", model, doi);
476
    }
477
    VIR_FREE(sec_managers);
478

479
    virObjectUnref(cfg);
480
    return caps;
481

482 483 484
no_memory:
    virReportOOMError();
err_exit:
485
    VIR_FREE(sec_managers);
486
    virCapabilitiesFree(caps);
487
    virObjectUnref(cfg);
488 489 490
    return NULL;
}

491

492 493
static int
qemuDomainSnapshotLoad(virDomainObjPtr vm,
494
                       void *data)
495
{
496 497 498 499 500 501 502
    char *baseDir = (char *)data;
    char *snapDir = NULL;
    DIR *dir = NULL;
    struct dirent *entry;
    char *xmlStr;
    char *fullpath;
    virDomainSnapshotDefPtr def = NULL;
503
    virDomainSnapshotObjPtr snap = NULL;
504
    virDomainSnapshotObjPtr current = NULL;
505
    char ebuf[1024];
506
    unsigned int flags = (VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE |
507
                          VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
508
                          VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL);
509
    int ret = -1;
510

511
    virObjectLock(vm);
512 513 514
    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);
515
        goto cleanup;
516 517
    }

518 519
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
520

521 522 523 524 525
    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)));
526
        goto cleanup;
527 528
    }

529 530 531
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
532

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

537
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
538
            VIR_ERROR(_("Failed to allocate memory for path"));
539 540
            continue;
        }
541

542
        if (virFileReadAll(fullpath, 1024*1024*1, &xmlStr) < 0) {
543 544 545 546 547 548
            /* 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;
        }
549

550 551 552
        def = virDomainSnapshotDefParseString(xmlStr, qemu_driver->caps,
                                              QEMU_EXPECTED_VIRT_TYPES,
                                              flags);
553 554
        if (def == NULL) {
            /* Nothing we can do here, skip this one */
555 556
            VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"),
                      fullpath);
557 558 559 560
            VIR_FREE(fullpath);
            VIR_FREE(xmlStr);
            continue;
        }
561

562
        snap = virDomainSnapshotAssignDef(vm->snapshots, def);
563 564
        if (snap == NULL) {
            virDomainSnapshotDefFree(def);
565 566 567 568
        } else if (snap->def->current) {
            current = snap;
            if (!vm->current_snapshot)
                vm->current_snapshot = snap;
569
        }
570

571 572
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
573 574
    }

575 576 577 578 579 580
    if (vm->current_snapshot != current) {
        VIR_ERROR(_("Too many snapshots claiming to be current for domain %s"),
                  vm->def->name);
        vm->current_snapshot = NULL;
    }

581
    if (virDomainSnapshotUpdateRelations(vm->snapshots) < 0)
582 583 584
        VIR_ERROR(_("Snapshots have inconsistent relations for domain %s"),
                  vm->def->name);

585 586 587 588 589 590 591 592
    /* 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.
     */
593

594
    virResetLastError();
595

596
    ret = 0;
597 598 599 600
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
601
    virObjectUnlock(vm);
602
    return ret;
603 604
}

605

606 607
static int
qemuDomainNetsRestart(virDomainObjPtr vm,
608
                      void *data ATTRIBUTE_UNUSED)
609
{
610 611 612
    int i;
    virDomainDefPtr def = vm->def;

613
    virObjectLock(vm);
614 615 616 617 618 619 620 621

    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,
622
                                                                 &net->mac,
623 624 625 626 627 628 629
                                                                 virDomainNetGetActualDirectDev(net),
                                                                 def->uuid,
                                                                 virDomainNetGetActualVirtPortProfile(net),
                                                                 VIR_NETDEV_VPORT_PROFILE_OP_CREATE));
        }
    }

630
    virObjectUnlock(vm);
631
    return 0;
632 633
}

634

635 636
static int
qemuDomainFindMaxID(virDomainObjPtr vm,
637 638 639 640 641 642
                    void *data)
{
    int *driver_maxid = data;

    if (vm->def->id >= *driver_maxid)
        *driver_maxid = vm->def->id + 1;
643 644

    return 0;
645 646 647
}


648
/**
649
 * qemuStartup:
650 651 652
 *
 * Initialization function for the QEmu daemon
 */
653
static int
654 655 656 657
qemuStartup(bool privileged,
            virStateInhibitCallback callback,
            void *opaque)
{
658 659 660
    char *driverConf = NULL;
    int rc;
    virConnectPtr conn = NULL;
661
    char ebuf[1024];
662 663
    char *membase = NULL;
    char *mempath = NULL;
664
    virQEMUDriverConfigPtr cfg;
665

666 667
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
668

669
    if (virMutexInit(&qemu_driver->lock) < 0) {
670
        VIR_ERROR(_("cannot initialize mutex"));
671 672
        VIR_FREE(qemu_driver);
        return -1;
673
    }
674
    qemuDriverLock(qemu_driver);
675

676 677
    qemu_driver->inhibitCallback = callback;
    qemu_driver->inhibitOpaque = opaque;
678

679 680
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
681

682 683
    if (!(qemu_driver->domains = virDomainObjListNew()))
        goto error;
684

685
    /* Init domain events */
686
    qemu_driver->domainEventState = virDomainEventStateNew();
687
    if (!qemu_driver->domainEventState)
688
        goto error;
689

690 691 692
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
693

694 695
    if (!(qemu_driver->config = cfg = virQEMUDriverConfigNew(privileged)))
        goto error;
696

697 698
    if (virAsprintf(&driverConf, "%s/qemu.conf", cfg->configBaseDir) < 0)
        goto out_of_memory;
699

700 701 702
    if (virQEMUDriverConfigLoadFile(cfg, driverConf) < 0)
        goto error;
    VIR_FREE(driverConf);
H
Hu Tao 已提交
703

704
    if (virFileMakePath(cfg->stateDir) < 0) {
705
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
706
                  cfg->stateDir, virStrerror(errno, ebuf, sizeof(ebuf)));
707
        goto error;
H
Hu Tao 已提交
708
    }
709
    if (virFileMakePath(cfg->libDir) < 0) {
710
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
711
                  cfg->libDir, virStrerror(errno, ebuf, sizeof(ebuf)));
712 713
        goto error;
    }
714
    if (virFileMakePath(cfg->cacheDir) < 0) {
715
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
716
                  cfg->cacheDir, virStrerror(errno, ebuf, sizeof(ebuf)));
717 718
        goto error;
    }
719
    if (virFileMakePath(cfg->saveDir) < 0) {
720
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
721
                  cfg->saveDir, virStrerror(errno, ebuf, sizeof(ebuf)));
722 723
        goto error;
    }
724
    if (virFileMakePath(cfg->snapshotDir) < 0) {
725
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
726
                  cfg->snapshotDir, virStrerror(errno, ebuf, sizeof(ebuf)));
727 728
        goto error;
    }
729
    if (virFileMakePath(cfg->autoDumpPath) < 0) {
730
        VIR_ERROR(_("Failed to create dump dir '%s': %s"),
731
                  cfg->autoDumpPath, virStrerror(errno, ebuf, sizeof(ebuf)));
732
        goto error;
733 734
    }

735 736 737
    rc = virCgroupForDriver("qemu", &qemu_driver->cgroup, privileged, 1);
    if (rc < 0) {
        VIR_INFO("Unable to create cgroup for driver: %s",
738
                 virStrerror(-rc, ebuf, sizeof(ebuf)));
739 740
    }

741 742 743 744 745 746 747

    if (!(qemu_driver->lockManager =
          virLockManagerPluginNew(cfg->lockManagerName ?
                                  cfg->lockManagerName : "nop",
                                  "qemu",
                                  cfg->configBaseDir,
                                  0)))
748
        goto error;
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

   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;
        }
   }
765

766 767 768
    /* Allocate bitmap for remote display port reservations. We cannot
     * do this before the config is loaded properly, since the port
     * numbers are configurable now */
769
    if ((qemu_driver->remotePorts =
770 771
         virPortAllocatorNew(cfg->remotePortMin,
                             cfg->remotePortMax)) == NULL)
772 773
        goto error;

774 775
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
776

777
    if ((qemu_driver->activePciHostdevs = virPCIDeviceListNew()) == NULL)
778
        goto error;
779

780 781 782
    if ((qemu_driver->activeUsbHostdevs = usbDeviceListNew()) == NULL)
        goto error;

783
    if ((qemu_driver->inactivePciHostdevs = virPCIDeviceListNew()) == NULL)
784 785
        goto error;

786 787 788
    if (!(qemu_driver->sharedDisks = virHashCreate(30, NULL)))
        goto error;

789
    if (privileged) {
790
        if (chown(cfg->libDir, cfg->user, cfg->group) < 0) {
791 792
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to user %d:%d"),
793
                                 cfg->libDir, cfg->user, cfg->group);
794
            goto error;
795
        }
796
        if (chown(cfg->cacheDir, cfg->user, cfg->group) < 0) {
797
            virReportSystemError(errno,
798
                                 _("unable to set ownership of '%s' to %d:%d"),
799
                                 cfg->cacheDir, cfg->user, cfg->group);
800
            goto error;
801
        }
802
        if (chown(cfg->saveDir, cfg->user, cfg->group) < 0) {
803 804
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
805
                                 cfg->saveDir, cfg->user, cfg->group);
806 807
            goto error;
        }
808
        if (chown(cfg->snapshotDir, cfg->user, cfg->group) < 0) {
809 810
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
811
                                 cfg->snapshotDir, cfg->user, cfg->group);
812
            goto error;
813
        }
814
    }
815

816 817 818
    qemu_driver->capsCache = qemuCapsCacheNew(cfg->libDir,
                                              cfg->user,
                                              cfg->group);
819 820 821
    if (!qemu_driver->capsCache)
        goto error;

822 823 824
    if ((qemu_driver->caps = qemuCreateCapabilities(qemu_driver)) == NULL)
        goto error;

825 826 827 828 829 830
    /* 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
831
     */
832 833
    if (cfg->hugetlbfsMount &&
        cfg->hugetlbfsMount[0] == '/') {
834
        if (virAsprintf(&membase, "%s/libvirt",
835
                        cfg->hugetlbfsMount) < 0 ||
836
            virAsprintf(&mempath, "%s/qemu", membase) < 0)
837
            goto out_of_memory;
838

839 840
        if (virFileMakePath(mempath) < 0) {
            virReportSystemError(errno,
841 842
                                 _("unable to create hugepage path %s"), mempath);
            goto error;
843
        }
844
        if (cfg->privileged) {
845 846
            if (virFileUpdatePerm(membase, 0, S_IXGRP | S_IXOTH) < 0)
                goto error;
847
            if (chown(mempath, cfg->user, cfg->group) < 0) {
848 849
                virReportSystemError(errno,
                                     _("unable to set ownership on %s to %d:%d"),
850 851
                                     mempath, cfg->user,
                                     cfg->group);
852 853
                goto error;
            }
G
Guido Günther 已提交
854
        }
S
Stefan Berger 已提交
855
        VIR_FREE(membase);
E
Eric Blake 已提交
856

857
        cfg->hugepagePath = mempath;
858
    }
859

860 861 862
    if (qemuDriverCloseCallbackInit(qemu_driver) < 0)
        goto error;

863
    /* Get all the running persistent or transient configs first */
864 865 866 867 868 869
    if (virDomainObjListLoadAllConfigs(qemu_driver->domains,
                                       qemu_driver->caps,
                                       cfg->stateDir,
                                       NULL,
                                       1, QEMU_EXPECTED_VIRT_TYPES,
                                       NULL, NULL) < 0)
870
        goto error;
871

872 873 874
    /* find the maximum ID from active and transient configs to initialize
     * the driver with. This is to avoid race between autostart and reconnect
     * threads */
875 876 877
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainFindMaxID,
                            &qemu_driver->nextvmid);
878

879 880 881
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainNetsRestart,
                            NULL);
882

883
    conn = virConnectOpen(cfg->uri);
884

885
    qemuProcessReconnectAll(conn, qemu_driver);
886

887
    /* Then inactive persistent configs */
888 889 890 891 892 893
    if (virDomainObjListLoadAllConfigs(qemu_driver->domains,
                                       qemu_driver->caps,
                                       cfg->configDir,
                                       cfg->autostartDir,
                                       0, QEMU_EXPECTED_VIRT_TYPES,
                                       NULL, NULL) < 0)
894
        goto error;
895

896

897 898 899
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainSnapshotLoad,
                            cfg->snapshotDir);
900

901 902 903
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainManagedSaveLoad,
                            qemu_driver);
904

905
    qemu_driver->workerPool = virThreadPoolNew(0, 1, 0, processWatchdogEvent, qemu_driver);
906 907
    if (!qemu_driver->workerPool)
        goto error;
908

909 910 911 912
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

913 914
    if (conn)
        virConnectClose(conn);
915

916
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
917
    return 0;
918

919 920 921 922 923 924 925 926
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(driverConf);
927 928
    VIR_FREE(membase);
    VIR_FREE(mempath);
929
    qemuShutdown();
930
    return -1;
931 932
}

933
static void qemuNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
934
{
935
    virQEMUDriverPtr driver = opaque;
936

937 938 939 940 941 942 943
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
944
    }
945
}
E
Eric Blake 已提交
946

947
/**
948
 * qemuReload:
949 950 951 952 953
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
954
qemuReload(void) {
955 956
    virQEMUDriverConfigPtr cfg;

957 958
    if (!qemu_driver)
        return 0;
959

960
    qemuDriverLock(qemu_driver);
961
    cfg = virQEMUDriverGetConfig(qemu_driver);
962 963 964 965 966 967
    virDomainObjListLoadAllConfigs(qemu_driver->domains,
                                   qemu_driver->caps,
                                   cfg->configDir,
                                   cfg->autostartDir,
                                   0, QEMU_EXPECTED_VIRT_TYPES,
                                   qemuNotifyLoadDomain, qemu_driver);
968
    qemuDriverUnlock(qemu_driver);
969
    virObjectUnref(cfg);
970 971
    return 0;
}
S
Stefan Berger 已提交
972

973 974 975 976 977 978 979 980 981 982 983

/*
 * qemuStop:
 *
 * Save any VMs in preparation for shutdown
 *
 */
static int
qemuStop(void) {
    int ret = -1;
    virConnectPtr conn;
984
    int numDomains = 0;
985 986 987 988
    size_t i;
    int state;
    virDomainPtr *domains = NULL;
    unsigned int *flags = NULL;
989
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(qemu_driver);
990

991 992
    if (!(conn = virConnectOpen(cfg->uri)))
        goto cleanup;
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

    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. */
    for (i = 0 ; i < numDomains ; i++) {
        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 */
    for (i = 0 ; i < numDomains ; i++)
        if (virDomainManagedSave(domains[i], flags[i]) < 0)
            ret = -1;

    VIR_FREE(domains);
    VIR_FREE(flags);

 cleanup:
    for (i = 0 ; i < numDomains ; i++)
        virDomainFree(domains[i]);
    VIR_FREE(domains);
    VIR_FREE(flags);
1031 1032 1033
    if (conn)
        virConnectClose(conn);
    virObjectUnref(cfg);
1034 1035 1036 1037

    return ret;
}

1038
/**
1039
 * qemuShutdown:
1040 1041 1042 1043
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
1044
qemuShutdown(void) {
1045 1046
    if (!qemu_driver)
        return -1;
1047

1048
    qemuDriverLock(qemu_driver);
1049
    virNWFilterUnRegisterCallbackDriver(&qemuCallbackDriver);
1050 1051
    virPCIDeviceListFree(qemu_driver->activePciHostdevs);
    virPCIDeviceListFree(qemu_driver->inactivePciHostdevs);
1052
    usbDeviceListFree(qemu_driver->activeUsbHostdevs);
1053
    virHashFree(qemu_driver->sharedDisks);
1054
    virCapabilitiesFree(qemu_driver->caps);
1055
    qemuCapsCacheFree(qemu_driver->capsCache);
1056

1057
    virObjectUnref(qemu_driver->domains);
1058
    virObjectUnref(qemu_driver->remotePorts);
1059

1060
    virSysinfoDefFree(qemu_driver->hostsysinfo);
1061

1062
    qemuDriverCloseCallbackShutdown(qemu_driver);
1063

E
Eric Blake 已提交
1064
    VIR_FREE(qemu_driver->qemuImgBinary);
1065

1066
    virSecurityManagerFree(qemu_driver->securityManager);
1067

1068
    ebtablesContextFree(qemu_driver->ebtables);
1069

1070
    /* Free domain callback list */
1071
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
1072

1073
    virCgroupFree(&qemu_driver->cgroup);
1074

1075 1076
    virLockManagerPluginUnref(qemu_driver->lockManager);

1077 1078 1079 1080
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
1081

1082
    return 0;
1083 1084
}

1085

1086 1087 1088
static virDrvOpenStatus qemuOpen(virConnectPtr conn,
                                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                 unsigned int flags)
1089
{
1090 1091
    virQEMUDriverConfigPtr cfg = NULL;
    virDrvOpenStatus ret = VIR_DRV_OPEN_ERROR;
E
Eric Blake 已提交
1092 1093
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1094
    if (conn->uri == NULL) {
1095 1096 1097 1098 1099 1100
        if (qemu_driver == NULL) {
            ret = VIR_DRV_OPEN_DECLINED;
            goto cleanup;
        }

        cfg = virQEMUDriverGetConfig(qemu_driver);
1101

1102 1103
        if (!(conn->uri = virURIParse(cfg->uri)))
            goto cleanup;
1104 1105 1106
    } else {
        /* If URI isn't 'qemu' its definitely not for us */
        if (conn->uri->scheme == NULL ||
1107 1108 1109 1110
            STRNEQ(conn->uri->scheme, "qemu")) {
            ret = VIR_DRV_OPEN_DECLINED;
            goto cleanup;
        }
1111 1112

        /* Allow remote driver to deal with URIs with hostname server */
1113 1114 1115 1116
        if (conn->uri->server != NULL) {
            ret = VIR_DRV_OPEN_DECLINED;
            goto cleanup;
        }
1117

1118
        if (qemu_driver == NULL) {
1119 1120
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("qemu state driver is not active"));
1121
            goto cleanup;
1122 1123
        }

1124
        if (conn->uri->path == NULL) {
1125 1126
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no QEMU URI path given, try %s"),
1127 1128
                           cfg->uri);
            goto cleanup;
1129 1130
        }

1131 1132
        cfg = virQEMUDriverGetConfig(qemu_driver);
        if (cfg->privileged) {
1133 1134
            if (STRNEQ(conn->uri->path, "/system") &&
                STRNEQ(conn->uri->path, "/session")) {
1135 1136 1137
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected QEMU URI path '%s', try qemu:///system"),
                               conn->uri->path);
1138
                goto cleanup;
1139 1140
            }
        } else {
1141
            if (STRNEQ(conn->uri->path, "/session")) {
1142 1143 1144
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected QEMU URI path '%s', try qemu:///session"),
                               conn->uri->path);
1145
                goto cleanup;
1146 1147
            }
        }
1148 1149 1150
    }
    conn->privateData = qemu_driver;

1151 1152 1153 1154
    ret = VIR_DRV_OPEN_SUCCESS;
cleanup:
    virObjectUnref(cfg);
    return ret;
1155 1156
}

1157
static int qemuClose(virConnectPtr conn) {
1158
    virQEMUDriverPtr driver = conn->privateData;
1159 1160

    /* Get rid of callbacks registered for this conn */
1161
    qemuDriverLock(driver);
1162
    qemuDriverCloseCallbackRunAll(driver, conn);
1163
    qemuDriverUnlock(driver);
1164 1165 1166 1167 1168 1169

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1170 1171
/* Which features are supported by this driver? */
static int
1172
qemuSupportsFeature(virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
D
Daniel Veillard 已提交
1173 1174
{
    switch (feature) {
1175
    case VIR_DRV_FEATURE_MIGRATION_V2:
1176
    case VIR_DRV_FEATURE_MIGRATION_V3:
1177
    case VIR_DRV_FEATURE_MIGRATION_P2P:
1178
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
1179
    case VIR_DRV_FEATURE_FD_PASSING:
1180
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
1181
    case VIR_DRV_FEATURE_XML_MIGRATABLE:
L
liguang 已提交
1182
    case VIR_DRV_FEATURE_MIGRATION_OFFLINE:
1183 1184 1185
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
1186 1187 1188
    }
}

1189
static const char *qemuGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1190
    return "QEMU";
1191 1192
}

1193

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
static int qemuIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}

static int qemuIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}

1206 1207 1208 1209 1210
static int qemuIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}

1211

1212 1213 1214 1215
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
1216

1217 1218
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1219
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
1220
        return -1;
1221 1222 1223 1224 1225 1226
    }

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

1227
    VIR_FORCE_CLOSE(fd);
1228 1229 1230 1231
    return maxvcpus;
}


E
Eric Blake 已提交
1232 1233 1234
static char *
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
{
1235
    virQEMUDriverPtr driver = conn->privateData;
1236
    virBuffer buf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
1237 1238 1239 1240

    virCheckFlags(0, NULL);

    if (!driver->hostsysinfo) {
1241 1242
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Host SMBIOS information is not available"));
E
Eric Blake 已提交
1243 1244 1245
        return NULL;
    }

1246 1247 1248 1249 1250 1251 1252
    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
E
Eric Blake 已提交
1253 1254
}

1255
static int qemuGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
1256 1257 1258
    if (!type)
        return 16;

1259
    if (STRCASEEQ(type, "qemu"))
1260 1261
        return 16;

1262
    if (STRCASEEQ(type, "kvm"))
1263
        return kvmGetMaxVCPUs();
1264

1265
    if (STRCASEEQ(type, "kqemu"))
1266
        return 1;
1267

1268 1269
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unknown type '%s'"), type);
1270 1271 1272
    return -1;
}

1273

1274
static char *qemuGetCapabilities(virConnectPtr conn) {
1275
    virQEMUDriverPtr driver = conn->privateData;
1276
    virCapsPtr caps = NULL;
1277
    char *xml = NULL;
1278

1279
    qemuDriverLock(driver);
1280

1281
    if ((caps = qemuCreateCapabilities(qemu_driver)) == NULL) {
1282 1283 1284
        virCapabilitiesFree(caps);
        goto cleanup;
    }
1285

1286
    virCapabilitiesFree(qemu_driver->caps);
1287 1288 1289
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1290
        virReportOOMError();
1291 1292

cleanup:
1293
    qemuDriverUnlock(driver);
1294

1295
    return xml;
1296 1297 1298
}


1299
static int
1300 1301
qemuGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, long *vm_rss,
                   pid_t pid, int tid)
1302 1303
{
    char *proc;
D
Daniel P. Berrange 已提交
1304
    FILE *pidinfo;
1305
    unsigned long long usertime, systime;
1306
    long rss;
1307 1308
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1309

1310 1311
    /* In general, we cannot assume pid_t fits in int; but /proc parsing
     * is specific to Linux where int works fine.  */
1312
    if (tid)
1313
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", (int) pid, tid);
1314
    else
1315
        ret = virAsprintf(&proc, "/proc/%d/stat", (int) pid);
1316
    if (ret < 0)
D
Daniel P. Berrange 已提交
1317 1318 1319 1320
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1321 1322 1323 1324
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1325 1326
        if (vm_rss)
            *vm_rss = 0;
1327
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1328 1329
        return 0;
    }
1330
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1331

1332 1333 1334 1335 1336 1337
    /* 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 */
1338
               "%*d %*d %*d %*d %*d %*d %*u %*u %ld %*u %*u %*u"
1339 1340
               /* startstack -> processor */
               "%*u %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %d",
1341
               &usertime, &systime, &rss, &cpu) != 4) {
1342
        VIR_FORCE_FCLOSE(pidinfo);
1343
        VIR_WARN("cannot parse process status data");
1344
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1345 1346 1347 1348 1349 1350 1351 1352
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1353 1354 1355 1356 1357
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

1358 1359 1360 1361 1362 1363
    /* 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 已提交
1364

1365 1366

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

1369
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1370 1371 1372 1373 1374

    return 0;
}


1375 1376
static virDomainPtr qemuDomainLookupByID(virConnectPtr conn,
                                         int id) {
1377
    virQEMUDriverPtr driver = conn->privateData;
1378 1379 1380
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1381
    qemuDriverLock(driver);
1382
    vm  = virDomainObjListFindByID(driver->domains, id);
1383
    qemuDriverUnlock(driver);
1384 1385

    if (!vm) {
1386 1387
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), id);
1388
        goto cleanup;
1389 1390
    }

1391
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1392
    if (dom) dom->id = vm->def->id;
1393 1394

cleanup:
1395
    if (vm)
1396
        virObjectUnlock(vm);
1397 1398
    return dom;
}
1399

1400 1401
static virDomainPtr qemuDomainLookupByUUID(virConnectPtr conn,
                                           const unsigned char *uuid) {
1402
    virQEMUDriverPtr driver = conn->privateData;
1403 1404
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1405

1406
    qemuDriverLock(driver);
1407
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
1408 1409
    qemuDriverUnlock(driver);

1410
    if (!vm) {
1411 1412
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1413 1414
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1415
        goto cleanup;
1416 1417
    }

1418
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1419
    if (dom) dom->id = vm->def->id;
1420 1421

cleanup:
1422
    if (vm)
1423
        virObjectUnlock(vm);
1424 1425
    return dom;
}
1426

1427 1428
static virDomainPtr qemuDomainLookupByName(virConnectPtr conn,
                                           const char *name) {
1429
    virQEMUDriverPtr driver = conn->privateData;
1430 1431
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1432

1433
    qemuDriverLock(driver);
1434
    vm = virDomainObjListFindByName(driver->domains, name);
1435 1436
    qemuDriverUnlock(driver);

1437
    if (!vm) {
1438 1439
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), name);
1440
        goto cleanup;
1441 1442
    }

1443
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1444
    if (dom) dom->id = vm->def->id;
1445 1446

cleanup:
1447
    if (vm)
1448
        virObjectUnlock(vm);
1449 1450 1451
    return dom;
}

1452 1453 1454 1455 1456 1457

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

1458
    if (!(obj = qemuDomObjFromDomain(dom)))
1459
        goto cleanup;
1460

1461 1462 1463 1464
    ret = virDomainObjIsActive(obj);

cleanup:
    if (obj)
1465
        virObjectUnlock(obj);
1466 1467 1468 1469 1470 1471 1472 1473
    return ret;
}

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

1474
    if (!(obj = qemuDomObjFromDomain(dom)))
1475
        goto cleanup;
1476

1477 1478 1479 1480
    ret = obj->persistent;

cleanup:
    if (obj)
1481
        virObjectUnlock(obj);
1482 1483 1484
    return ret;
}

1485 1486 1487 1488 1489
static int qemuDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

1490
    if (!(obj = qemuDomObjFromDomain(dom)))
1491
        goto cleanup;
1492

1493 1494 1495 1496
    ret = obj->updated;

cleanup:
    if (obj)
1497
        virObjectUnlock(obj);
1498 1499
    return ret;
}
1500

1501
static int qemuGetVersion(virConnectPtr conn, unsigned long *version) {
1502
    virQEMUDriverPtr driver = conn->privateData;
1503
    int ret = -1;
1504
    unsigned int qemuVersion;
1505

1506
    qemuDriverLock(driver);
1507 1508
    if (qemuCapsGetDefaultVersion(driver->caps,
                                  driver->capsCache,
1509
                                  &qemuVersion) < 0)
1510
        goto cleanup;
1511

1512
    *version = qemuVersion;
1513 1514 1515
    ret = 0;

cleanup:
1516
    qemuDriverUnlock(driver);
1517
    return ret;
D
Daniel P. Berrange 已提交
1518 1519
}

1520
static int qemuListDomains(virConnectPtr conn, int *ids, int nids) {
1521
    virQEMUDriverPtr driver = conn->privateData;
1522
    int n;
1523

1524
    qemuDriverLock(driver);
1525
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids);
1526
    qemuDriverUnlock(driver);
1527

1528
    return n;
D
Daniel P. Berrange 已提交
1529
}
1530

1531
static int qemuNumDomains(virConnectPtr conn) {
1532
    virQEMUDriverPtr driver = conn->privateData;
1533
    int n;
1534

1535
    qemuDriverLock(driver);
1536
    n = virDomainObjListNumOfDomains(driver->domains, 1);
1537
    qemuDriverUnlock(driver);
1538

1539
    return n;
D
Daniel P. Berrange 已提交
1540
}
1541

1542 1543 1544 1545

static int
qemuCanonicalizeMachine(virDomainDefPtr def, qemuCapsPtr caps)
{
1546
    const char *canon;
1547

1548 1549 1550 1551
    if (!(canon = qemuCapsGetCanonicalMachine(caps, def->os.machine)))
        return 0;

    if (STRNEQ(canon, def->os.machine)) {
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
        char *tmp;
        if (!(tmp = strdup(canon))) {
            virReportOOMError();
            return -1;
        }
        VIR_FREE(def->os.machine);
        def->os.machine = tmp;
    }

    return 0;
}


1565 1566
static virDomainPtr qemuDomainCreate(virConnectPtr conn, const char *xml,
                                     unsigned int flags) {
1567
    virQEMUDriverPtr driver = conn->privateData;
1568
    virDomainDefPtr def;
1569
    virDomainObjPtr vm = NULL;
1570
    virDomainPtr dom = NULL;
1571
    virDomainEventPtr event = NULL;
1572
    virDomainEventPtr event2 = NULL;
1573
    unsigned int start_flags = VIR_QEMU_PROCESS_START_COLD;
1574
    qemuCapsPtr caps = NULL;
D
Daniel P. Berrange 已提交
1575

1576 1577
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1578

1579 1580 1581 1582 1583
    if (flags & VIR_DOMAIN_START_PAUSED)
        start_flags |= VIR_QEMU_PROCESS_START_PAUSED;
    if (flags & VIR_DOMAIN_START_AUTODESTROY)
        start_flags |= VIR_QEMU_PROCESS_START_AUTODESROY;

1584
    qemuDriverLock(driver);
1585
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1586
                                        QEMU_EXPECTED_VIRT_TYPES,
1587
                                        VIR_DOMAIN_XML_INACTIVE)))
1588
        goto cleanup;
1589

1590
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1591 1592
        goto cleanup;

1593 1594 1595
    if (!(caps = qemuCapsCacheLookup(driver->capsCache, def->emulator)))
        goto cleanup;

1596
    if (qemuCanonicalizeMachine(def, caps) < 0)
1597 1598
        goto cleanup;

1599
    if (qemuDomainAssignAddresses(def, caps, NULL) < 0)
1600 1601
        goto cleanup;

1602 1603
    if (!(vm = virDomainObjListAdd(driver->domains,
                                   driver->caps,
1604 1605 1606
                                   def,
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1607 1608 1609
        goto cleanup;

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

1611
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1612 1613
        goto cleanup; /* XXXX free the 'vm' we created ? */

1614 1615 1616
    if (qemuProcessStart(conn, driver, vm, NULL, -1, NULL, NULL,
                         VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
                         start_flags) < 0) {
1617
        virDomainAuditStart(vm, "booted", false);
1618
        if (qemuDomainObjEndJob(driver, vm) > 0)
1619
            qemuDomainRemoveInactive(driver, vm);
1620
        vm = NULL;
1621
        goto cleanup;
D
Daniel P. Berrange 已提交
1622
    }
1623 1624 1625 1626

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    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);
    }
1637
    virDomainAuditStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1638

1639
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1640
    if (dom) dom->id = vm->def->id;
1641

1642
    if (vm &&
1643
        qemuDomainObjEndJob(driver, vm) == 0)
1644
        vm = NULL;
1645

1646 1647
cleanup:
    virDomainDefFree(def);
1648
    if (vm)
1649
        virObjectUnlock(vm);
1650
    if (event) {
1651
        qemuDomainEventQueue(driver, event);
1652 1653 1654
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
1655
    virObjectUnref(caps);
1656
    qemuDriverUnlock(driver);
1657
    return dom;
D
Daniel P. Berrange 已提交
1658 1659 1660
}


1661
static int qemuDomainSuspend(virDomainPtr dom) {
1662
    virQEMUDriverPtr driver = dom->conn->privateData;
1663 1664
    virDomainObjPtr vm;
    int ret = -1;
1665
    virDomainEventPtr event = NULL;
1666
    qemuDomainObjPrivatePtr priv;
1667 1668
    virDomainPausedReason reason;
    int eventDetail;
1669
    int state;
1670
    virQEMUDriverConfigPtr cfg = NULL;
1671

1672
    qemuDriverLock(driver);
1673
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1674

D
Daniel P. Berrange 已提交
1675
    if (!vm) {
1676 1677
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1678 1679
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1680
        goto cleanup;
D
Daniel P. Berrange 已提交
1681
    }
D
Daniel P. Berrange 已提交
1682
    if (!virDomainObjIsActive(vm)) {
1683 1684
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1685
        goto cleanup;
D
Daniel P. Berrange 已提交
1686
    }
1687

1688
    cfg = virQEMUDriverGetConfig(driver);
1689 1690
    priv = vm->privateData;

1691 1692 1693 1694
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_SUSPEND) < 0)
        goto cleanup;

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

1700 1701 1702
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1703 1704 1705
    } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_SNAPSHOT) {
        reason = VIR_DOMAIN_PAUSED_SNAPSHOT;
        eventDetail = -1; /* don't create lifecycle events when doing snapshot */
1706 1707 1708 1709 1710
    } else {
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }

1711 1712 1713 1714 1715 1716
    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) {
1717
        if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1718
            goto endjob;
1719
        }
1720 1721 1722 1723 1724 1725

        if (eventDetail >= 0) {
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             eventDetail);
        }
D
Daniel P. Berrange 已提交
1726
    }
1727
    if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0)
1728 1729
        goto endjob;
    ret = 0;
1730

1731
endjob:
1732
    if (qemuDomainObjEndJob(driver, vm) == 0)
1733
        vm = NULL;
1734

1735
cleanup:
1736
    if (vm)
1737
        virObjectUnlock(vm);
1738

1739
    if (event)
1740
        qemuDomainEventQueue(driver, event);
1741
    qemuDriverUnlock(driver);
1742
    virObjectUnref(cfg);
1743
    return ret;
D
Daniel P. Berrange 已提交
1744 1745 1746
}


1747
static int qemuDomainResume(virDomainPtr dom) {
1748
    virQEMUDriverPtr driver = dom->conn->privateData;
1749 1750
    virDomainObjPtr vm;
    int ret = -1;
1751
    virDomainEventPtr event = NULL;
1752
    int state;
1753
    virQEMUDriverConfigPtr cfg = NULL;
1754

1755
    qemuDriverLock(driver);
1756
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1757

D
Daniel P. Berrange 已提交
1758
    if (!vm) {
1759 1760
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1761 1762
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1763
        goto cleanup;
D
Daniel P. Berrange 已提交
1764
    }
1765

1766 1767
    cfg = virQEMUDriverGetConfig(driver);

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

D
Daniel P. Berrange 已提交
1771
    if (!virDomainObjIsActive(vm)) {
1772 1773
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1774
        goto endjob;
D
Daniel P. Berrange 已提交
1775
    }
1776 1777 1778 1779 1780 1781 1782

    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 已提交
1783
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
1784 1785
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
1786
            if (virGetLastError() == NULL)
1787 1788
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("resume operation failed"));
1789
            goto endjob;
1790
        }
1791 1792 1793
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
1794
    }
1795
    if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0)
1796
        goto endjob;
1797 1798
    ret = 0;

1799
endjob:
1800
    if (qemuDomainObjEndJob(driver, vm) == 0)
1801
        vm = NULL;
1802

1803
cleanup:
1804
    if (vm)
1805
        virObjectUnlock(vm);
1806
    if (event)
1807
        qemuDomainEventQueue(driver, event);
1808
    qemuDriverUnlock(driver);
1809
    virObjectUnref(cfg);
1810
    return ret;
D
Daniel P. Berrange 已提交
1811 1812
}

1813
static int qemuDomainShutdownFlags(virDomainPtr dom, unsigned int flags) {
1814
    virQEMUDriverPtr driver = dom->conn->privateData;
1815 1816
    virDomainObjPtr vm;
    int ret = -1;
1817
    qemuDomainObjPrivatePtr priv;
1818 1819 1820 1821
    bool useAgent = false;

    virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
                  VIR_DOMAIN_SHUTDOWN_GUEST_AGENT, -1);
1822

1823 1824 1825 1826 1827 1828 1829 1830
    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN) &&
        (flags & VIR_DOMAIN_SHUTDOWN_GUEST_AGENT)) {
        virReportInvalidArg(flags, "%s",
                            _("flags for acpi power button and guest agent are mutually exclusive"));
        return -1;
    }

1831
    if (!(vm = qemuDomObjFromDomain(dom)))
1832
        goto cleanup;
1833

1834 1835 1836 1837 1838 1839 1840 1841 1842
    priv = vm->privateData;

    if ((flags & VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) ||
        (!(flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN) &&
         priv->agent))
        useAgent = true;

    if (useAgent) {
        if (priv->agentError) {
1843 1844 1845
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                           _("QEMU guest agent is not "
                             "available due to an error"));
1846
            goto cleanup;
1847 1848
        }
        if (!priv->agent) {
1849 1850
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
1851
            goto cleanup;
1852 1853 1854
        }
    }

1855
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1856 1857
        goto cleanup;

D
Daniel P. Berrange 已提交
1858
    if (!virDomainObjIsActive(vm)) {
1859 1860
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1861
        goto endjob;
1862 1863
    }

1864 1865 1866 1867 1868 1869
    if (useAgent) {
        qemuDomainObjEnterAgent(driver, vm);
        ret = qemuAgentShutdown(priv->agent, QEMU_AGENT_SHUTDOWN_POWERDOWN);
        qemuDomainObjExitAgent(driver, vm);
    } else {
        qemuDomainSetFakeReboot(driver, vm, false);
1870

1871 1872 1873 1874
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSystemPowerdown(priv->mon);
        qemuDomainObjExitMonitor(driver, vm);
    }
1875

1876
endjob:
1877
    if (qemuDomainObjEndJob(driver, vm) == 0)
1878
        vm = NULL;
1879

1880
cleanup:
1881
    if (vm)
1882
        virObjectUnlock(vm);
1883
    return ret;
1884 1885
}

1886 1887
static int qemuDomainShutdown(virDomainPtr dom)
{
1888 1889 1890
    return qemuDomainShutdownFlags(dom, 0);
}

1891

1892 1893 1894
static int
qemuDomainReboot(virDomainPtr dom, unsigned int flags)
{
1895
    virQEMUDriverPtr driver = dom->conn->privateData;
1896 1897 1898
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
1899
    bool useAgent = false;
1900

1901 1902
    virCheckFlags(VIR_DOMAIN_REBOOT_ACPI_POWER_BTN |
                  VIR_DOMAIN_REBOOT_GUEST_AGENT , -1);
1903

1904 1905 1906 1907 1908 1909 1910 1911
    /* 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;
    }

1912
    if (!(vm = qemuDomObjFromDomain(dom)))
1913 1914
        goto cleanup;

1915 1916
    priv = vm->privateData;

1917 1918
    if ((flags & VIR_DOMAIN_REBOOT_GUEST_AGENT) ||
        (!(flags & VIR_DOMAIN_REBOOT_ACPI_POWER_BTN) &&
1919 1920 1921 1922 1923
         priv->agent))
        useAgent = true;

    if (useAgent) {
        if (priv->agentError) {
1924 1925 1926
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                           _("QEMU guest agent is not "
                             "available due to an error"));
1927 1928 1929
            goto cleanup;
        }
        if (!priv->agent) {
1930 1931
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
1932 1933 1934
            goto cleanup;
        }
    } else {
1935
#if WITH_YAJL
1936 1937
        if (qemuCapsGet(priv->caps, QEMU_CAPS_MONITOR_JSON)) {
            if (!qemuCapsGet(priv->caps, QEMU_CAPS_NO_SHUTDOWN)) {
1938 1939
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Reboot is not supported with this QEMU binary"));
1940 1941 1942 1943
                goto cleanup;
            }
        } else {
#endif
1944 1945
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Reboot is not supported without the JSON monitor"));
1946
            goto cleanup;
1947
#if WITH_YAJL
1948
        }
1949 1950
#endif
    }
1951

1952 1953
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
1954

1955
    if (!virDomainObjIsActive(vm)) {
1956 1957
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1958 1959
        goto endjob;
    }
1960

1961 1962 1963 1964 1965
    if (useAgent) {
        qemuDomainObjEnterAgent(driver, vm);
        ret = qemuAgentShutdown(priv->agent, QEMU_AGENT_SHUTDOWN_REBOOT);
        qemuDomainObjExitAgent(driver, vm);
    } else {
1966
        qemuDomainObjEnterMonitor(driver, vm);
1967
        ret = qemuMonitorSystemPowerdown(priv->mon);
1968
        qemuDomainObjExitMonitor(driver, vm);
1969

1970 1971
        if (ret == 0)
            qemuDomainSetFakeReboot(driver, vm, true);
1972 1973
    }

1974 1975 1976 1977
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

1978 1979
cleanup:
    if (vm)
1980
        virObjectUnlock(vm);
1981 1982 1983 1984
    return ret;
}


1985 1986 1987
static int
qemuDomainReset(virDomainPtr dom, unsigned int flags)
{
1988
    virQEMUDriverPtr driver = dom->conn->privateData;
1989 1990 1991 1992 1993 1994
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

1995
    if (!(vm = qemuDomObjFromDomain(dom)))
1996 1997 1998 1999 2000 2001
        goto cleanup;

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

    if (!virDomainObjIsActive(vm)) {
2002 2003
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
        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)
2020
        virObjectUnlock(vm);
2021 2022 2023 2024
    return ret;
}


2025
/* Count how many snapshots in a set are external snapshots or checkpoints.  */
2026 2027 2028 2029 2030 2031 2032 2033
static void
qemuDomainSnapshotCountExternal(void *payload,
                                const void *name ATTRIBUTE_UNUSED,
                                void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    int *count = data;

2034
    if (virDomainSnapshotIsExternal(snap))
2035 2036 2037
        (*count)++;
}

2038 2039 2040 2041
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
2042
    virQEMUDriverPtr driver = dom->conn->privateData;
2043 2044
    virDomainObjPtr vm;
    int ret = -1;
2045
    virDomainEventPtr event = NULL;
2046
    qemuDomainObjPrivatePtr priv;
2047

2048
    virCheckFlags(VIR_DOMAIN_DESTROY_GRACEFUL, -1);
2049

2050
    qemuDriverLock(driver);
2051
    vm  = virDomainObjListFindByUUID(driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
2052
    if (!vm) {
2053 2054
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2055 2056
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
2057
        goto cleanup;
D
Daniel P. Berrange 已提交
2058
    }
2059

2060 2061
    priv = vm->privateData;

2062
    qemuDomainSetFakeReboot(driver, vm, false);
2063

2064 2065 2066 2067 2068 2069

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

2070 2071 2072 2073 2074
    /* 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
     */
2075
    if (flags & VIR_DOMAIN_DESTROY_GRACEFUL) {
2076 2077
        if (qemuProcessKill(driver, vm, 0) < 0) {
            priv->beingDestroyed = false;
2078
            goto cleanup;
2079
        }
2080
    } else {
2081 2082
        if (qemuProcessKill(driver, vm, VIR_QEMU_PROCESS_KILL_FORCE) < 0) {
            priv->beingDestroyed = false;
2083
            goto cleanup;
2084
        }
2085
    }
2086

2087
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
2088 2089
        goto cleanup;

2090 2091
    priv->beingDestroyed = false;

D
Daniel P. Berrange 已提交
2092
    if (!virDomainObjIsActive(vm)) {
2093 2094
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2095
        goto endjob;
2096
    }
2097

2098
    qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED, 0);
2099 2100 2101
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
2102
    virDomainAuditStop(vm, "destroyed");
2103

2104
    if (!vm->persistent) {
2105
        if (qemuDomainObjEndJob(driver, vm) > 0)
2106
            qemuDomainRemoveInactive(driver, vm);
2107 2108
        vm = NULL;
    }
2109 2110
    ret = 0;

2111
endjob:
2112
    if (vm &&
2113
        qemuDomainObjEndJob(driver, vm) == 0)
2114
        vm = NULL;
2115

2116
cleanup:
2117
    if (vm)
2118
        virObjectUnlock(vm);
2119 2120
    if (event)
        qemuDomainEventQueue(driver, event);
2121
    qemuDriverUnlock(driver);
2122
    return ret;
D
Daniel P. Berrange 已提交
2123 2124
}

2125 2126 2127 2128 2129
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
2130

2131
static char *qemuDomainGetOSType(virDomainPtr dom) {
2132 2133
    virDomainObjPtr vm;
    char *type = NULL;
2134

2135
    if (!(vm = qemuDomObjFromDomain(dom)))
2136
        goto cleanup;
2137

2138
    if (!(type = strdup(vm->def->os.type)))
2139
        virReportOOMError();
2140 2141

cleanup:
2142
    if (vm)
2143
        virObjectUnlock(vm);
2144 2145 2146
    return type;
}

2147
/* Returns max memory in kb, 0 if error */
2148 2149 2150
static unsigned long long
qemuDomainGetMaxMemory(virDomainPtr dom)
{
2151
    virDomainObjPtr vm;
2152
    unsigned long long ret = 0;
2153

2154
    if (!(vm = qemuDomObjFromDomain(dom)))
2155
        goto cleanup;
2156

2157
    ret = vm->def->mem.max_balloon;
2158 2159

cleanup:
2160
    if (vm)
2161
        virObjectUnlock(vm);
2162
    return ret;
2163 2164
}

2165 2166
static int qemuDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                    unsigned int flags) {
2167
    virQEMUDriverPtr driver = dom->conn->privateData;
2168
    qemuDomainObjPrivatePtr priv;
2169
    virDomainObjPtr vm;
2170
    virDomainDefPtr persistentDef = NULL;
2171
    int ret = -1, r;
2172
    virQEMUDriverConfigPtr cfg = NULL;
2173

2174 2175
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
2176
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
2177

2178
    if (!(vm = qemuDomObjFromDomain(dom)))
2179
        goto cleanup;
2180

2181 2182
    cfg = virQEMUDriverGetConfig(driver);

2183
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2184 2185
        goto cleanup;

2186 2187
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
2188
        goto endjob;
2189

2190 2191 2192
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

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

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

2210 2211 2212 2213
    } else {
        /* resize the current memory */

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

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

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

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

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

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

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

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

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

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
2278
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
2279 2280 2281
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
2282 2283
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
2284 2285 2286 2287
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2288 2289
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2290 2291 2292 2293 2294
        goto cleanup;
    }

    priv = vm->privateData;

2295
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
2296
        goto cleanup;
2297 2298

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

2304
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2305 2306
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2307 2308

endjob:
2309
    if (qemuDomainObjEndJob(driver, vm) == 0) {
2310 2311 2312 2313 2314 2315
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
2316
        virObjectUnlock(vm);
2317 2318 2319 2320
    qemuDriverUnlock(driver);
    return ret;
}

2321 2322 2323 2324 2325 2326 2327
static int qemuDomainSendKey(virDomainPtr domain,
                             unsigned int codeset,
                             unsigned int holdtime,
                             unsigned int *keycodes,
                             int nkeycodes,
                             unsigned int flags)
{
2328
    virQEMUDriverPtr driver = domain->conn->privateData;
2329 2330 2331 2332 2333 2334
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

2335 2336
    /* translate the keycode to RFB for qemu driver */
    if (codeset != VIR_KEYCODE_SET_RFB) {
2337 2338 2339 2340
        int i;
        int keycode;

        for (i = 0; i < nkeycodes; i++) {
2341
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_RFB,
2342 2343
                                               keycodes[i]);
            if (keycode < 0) {
2344 2345 2346 2347
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot translate keycode %u of %s codeset to rfb keycode"),
                               keycodes[i],
                               virKeycodeSetTypeToString(codeset));
2348 2349 2350 2351 2352 2353
                return -1;
            }
            keycodes[i] = keycode;
        }
    }

2354
    if (!(vm = qemuDomObjFromDomain(domain)))
2355 2356 2357 2358
        goto cleanup;

    priv = vm->privateData;

2359
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2360 2361 2362
        goto cleanup;

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

2368
    qemuDomainObjEnterMonitor(driver, vm);
2369
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
2370
    qemuDomainObjExitMonitor(driver, vm);
2371 2372 2373

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
2374 2375 2376 2377
        vm = NULL;

cleanup:
    if (vm)
2378
        virObjectUnlock(vm);
2379 2380 2381
    return ret;
}

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

2391
    if (!(vm = qemuDomObjFromDomain(dom)))
2392
        goto cleanup;
D
Daniel P. Berrange 已提交
2393

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 (qemuCapsGet(priv->caps, 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;

J
Jiri Denemark 已提交
2473
    *state = virDomainObjGetState(vm, reason);
2474 2475 2476 2477
    ret = 0;

cleanup:
    if (vm)
2478
        virObjectUnlock(vm);
2479 2480 2481
    return ret;
}

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

    virCheckFlags(0, -1);

2493
    if (!(vm = qemuDomObjFromDomain(dom)))
2494 2495 2496
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
2497 2498
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2499 2500 2501 2502 2503 2504 2505 2506 2507
        goto cleanup;
    }

    priv = vm->privateData;

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

    if (priv->monError) {
        info->state = VIR_DOMAIN_CONTROL_ERROR;
2508
    } else if (priv->job.active) {
2509 2510
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
2511
            if (virTimeMillisNow(&info->stateTime) < 0)
2512
                goto cleanup;
2513
            info->stateTime -= priv->job.start;
2514 2515
        } else {
            info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
2516
            if (virTimeMillisNow(&info->stateTime) < 0)
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
                goto cleanup;
            info->stateTime -= priv->monStart;
        }
    } else {
        info->state = VIR_DOMAIN_CONTROL_OK;
    }

    ret = 0;

cleanup:
    if (vm)
2528
        virObjectUnlock(vm);
2529 2530 2531
    return ret;
}

D
Daniel P. Berrange 已提交
2532

2533 2534 2535 2536 2537 2538
/* 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
2539

2540
verify(sizeof(QEMU_SAVE_MAGIC) == sizeof(QEMU_SAVE_PARTIAL));
E
Eric Blake 已提交
2541

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

2556
    QEMU_SAVE_FORMAT_LAST
2557
} virQEMUSaveFormat;
2558

2559 2560
VIR_ENUM_DECL(qemuSaveCompression)
VIR_ENUM_IMPL(qemuSaveCompression, QEMU_SAVE_FORMAT_LAST,
2561 2562 2563
              "raw",
              "gzip",
              "bzip2",
2564 2565
              "xz",
              "lzop")
2566

2567 2568 2569
typedef struct _virQEMUSaveHeader virQEMUSaveHeader;
typedef virQEMUSaveHeader *virQEMUSaveHeaderPtr;
struct _virQEMUSaveHeader {
2570
    char magic[sizeof(QEMU_SAVE_MAGIC)-1];
2571 2572 2573 2574 2575
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2576 2577
};

2578
static inline void
2579
bswap_header(virQEMUSaveHeaderPtr hdr) {
2580 2581 2582 2583 2584 2585 2586
    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);
}


2587
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2588
static int
2589
qemuDomainSaveHeader(int fd, const char *path, const char *xml,
2590
                     virQEMUSaveHeaderPtr header)
E
Eric Blake 已提交
2591
{
2592 2593
    int ret = 0;

E
Eric Blake 已提交
2594
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2595
        ret = -errno;
2596 2597 2598
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("failed to write header to domain save file '%s'"),
                       path);
2599 2600 2601
        goto endjob;
    }

E
Eric Blake 已提交
2602
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2603
        ret = -errno;
2604 2605
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("failed to write xml to '%s'"), path);
2606 2607 2608 2609 2610 2611
        goto endjob;
    }
endjob:
    return ret;
}

2612
/* Given a virQEMUSaveFormat compression level, return the name
2613 2614 2615 2616
 * of the program to run, or NULL if no program is needed.  */
static const char *
qemuCompressProgramName(int compress)
{
2617 2618
    return (compress == QEMU_SAVE_FORMAT_RAW ? NULL :
            qemuSaveCompressionTypeToString(compress));
2619 2620
}

E
Eric Blake 已提交
2621 2622 2623
/* Internal function to properly create or open existing files, with
 * ownership affected by qemu driver setup.  */
static int
2624
qemuOpenFile(virQEMUDriverPtr driver, const char *path, int oflags,
E
Eric Blake 已提交
2625 2626 2627 2628 2629 2630
             bool *needUnlink, bool *bypassSecurityDriver)
{
    struct stat sb;
    bool is_reg = true;
    bool need_unlink = false;
    bool bypass_security = false;
L
Laine Stump 已提交
2631
    unsigned int vfoflags = 0;
E
Eric Blake 已提交
2632
    int fd = -1;
2633
    int path_shared = virStorageFileIsSharedFS(path);
E
Eric Blake 已提交
2634 2635
    uid_t uid = getuid();
    gid_t gid = getgid();
2636
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
E
Eric Blake 已提交
2637 2638 2639 2640 2641 2642

    /* 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;
2643 2644 2645

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

E
Eric Blake 已提交
2649 2650 2651 2652 2653
        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 */
2654
            if (is_reg && !cfg->dynamicOwnership) {
E
Eric Blake 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
                uid = sb.st_uid;
                gid = sb.st_gid;
            }
        }
    }

    /* First try creating the file as root */
    if (!is_reg) {
        fd = open(path, oflags & ~O_CREAT);
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
            goto cleanup;
        }
    } else {
L
Laine Stump 已提交
2669 2670
        if ((fd = virFileOpenAs(path, oflags, S_IRUSR | S_IWUSR, uid, gid,
                                vfoflags | VIR_FILE_OPEN_NOFORK)) < 0) {
E
Eric Blake 已提交
2671 2672 2673
            /* 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
2674
               qemu user (cfg->user) is non-root, just set a flag to
E
Eric Blake 已提交
2675 2676 2677
               bypass security driver shenanigans, and retry the operation
               after doing setuid to qemu user */
            if ((fd != -EACCES && fd != -EPERM) ||
2678
                cfg->user == getuid()) {
E
Eric Blake 已提交
2679 2680 2681 2682 2683 2684 2685
                virReportSystemError(-fd,
                                     _("Failed to create file '%s'"),
                                     path);
                goto cleanup;
            }

            /* On Linux we can also verify the FS-type of the directory. */
2686
            switch (path_shared) {
E
Eric Blake 已提交
2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
                case 1:
                   /* it was on a network share, so we'll continue
                    * as outlined above
                    */
                   break;

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

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

2709
            /* Retry creating the file as cfg->user */
E
Eric Blake 已提交
2710 2711 2712

            if ((fd = virFileOpenAs(path, oflags,
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
2713
                                    cfg->user, cfg->group,
L
Laine Stump 已提交
2714
                                    vfoflags | VIR_FILE_OPEN_FORK)) < 0) {
E
Eric Blake 已提交
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
                goto cleanup;
            }

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

            bypass_security = true;
        }
    }
cleanup:
    if (needUnlink)
        *needUnlink = need_unlink;
    if (bypassSecurityDriver)
        *bypassSecurityDriver = bypass_security;
2733
    virObjectUnref(cfg);
E
Eric Blake 已提交
2734 2735 2736
    return fd;
}

2737 2738 2739
/* 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 */
2740
static int
2741
qemuDomainSaveMemory(virQEMUDriverPtr driver,
2742 2743
                     virDomainObjPtr vm,
                     const char *path,
2744
                     const char *domXML,
2745 2746 2747 2748
                     int compressed,
                     bool was_running,
                     unsigned int flags,
                     enum qemuDomainAsyncJob asyncJob)
2749
{
2750
    virQEMUSaveHeader header;
2751
    bool bypassSecurityDriver = false;
E
Eric Blake 已提交
2752
    bool needUnlink = false;
2753
    int ret = -1;
2754
    int fd = -1;
2755
    int directFlag = 0;
J
Jiri Denemark 已提交
2756
    virFileWrapperFdPtr wrapperFd = NULL;
2757
    unsigned int wrapperFlags = VIR_FILE_WRAPPER_NON_BLOCKING;
2758 2759 2760
    unsigned long long pad;
    unsigned long long offset;
    size_t len;
2761
    char *xml = NULL;
2762

2763
    memset(&header, 0, sizeof(header));
2764 2765
    memcpy(header.magic, QEMU_SAVE_PARTIAL, sizeof(header.magic));
    header.version = QEMU_SAVE_VERSION;
2766
    header.was_running = was_running ? 1 : 0;
2767

2768
    header.compressed = compressed;
2769

2770
    len = strlen(domXML) + 1;
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
    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));
2784
    if (VIR_ALLOC_N(xml, len + pad) < 0) {
2785
        virReportOOMError();
2786
        goto cleanup;
2787
    }
2788 2789
    strcpy(xml, domXML);

2790 2791
    offset += pad;
    header.xml_len = len;
2792

2793
    /* Obtain the file handle.  */
2794 2795
    if ((flags & VIR_DOMAIN_SAVE_BYPASS_CACHE)) {
        wrapperFlags |= VIR_FILE_WRAPPER_BYPASS_CACHE;
2796 2797
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
2798 2799
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("bypass cache unsupported by this system"));
E
Eric Blake 已提交
2800
            goto cleanup;
2801
        }
2802
    }
E
Eric Blake 已提交
2803 2804 2805
    fd = qemuOpenFile(driver, path, O_WRONLY | O_TRUNC | O_CREAT | directFlag,
                      &needUnlink, &bypassSecurityDriver);
    if (fd < 0)
2806 2807
        goto cleanup;

2808
    if (!(wrapperFd = virFileWrapperFdNew(&fd, path, wrapperFlags)))
2809
        goto cleanup;
2810

2811
    /* Write header to file, followed by XML */
2812 2813
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0)
        goto cleanup;
2814

2815
    /* Perform the migration */
2816
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2817
                            qemuCompressProgramName(compressed),
E
Eric Blake 已提交
2818
                            bypassSecurityDriver,
2819 2820
                            asyncJob) < 0)
        goto cleanup;
E
Eric Blake 已提交
2821

2822 2823 2824 2825 2826 2827 2828 2829
    /* 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);
2830
        goto cleanup;
E
Eric Blake 已提交
2831
    }
2832

2833
    if (virFileWrapperFdClose(wrapperFd) < 0)
2834 2835 2836 2837
        goto cleanup;

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

2839
    memcpy(header.magic, QEMU_SAVE_MAGIC, sizeof(header.magic));
2840

E
Eric Blake 已提交
2841 2842
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        virReportSystemError(errno, _("unable to write %s"), path);
2843
        goto cleanup;
E
Eric Blake 已提交
2844
    }
2845

2846 2847
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2848
        goto cleanup;
2849 2850
    }

2851 2852
    ret = 0;

2853 2854
cleanup:
    VIR_FORCE_CLOSE(fd);
2855
    virFileWrapperFdCatchError(wrapperFd);
2856
    virFileWrapperFdFree(wrapperFd);
2857
    VIR_FREE(xml);
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871

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

    return ret;
}

/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active + locked. Vm will be unlocked and
 * potentially free'd after this returns (eg transient VMs are freed
 * shutdown). So 'vm' must not be referenced by the caller after
 * this returns (whether returning success or failure).
 */
static int
2872
qemuDomainSaveInternal(virQEMUDriverPtr driver, virDomainPtr dom,
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
                       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;

2883
    if (!qemuMigrationIsAllowed(driver, vm, vm->def, false))
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
        goto cleanup;

    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             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;

        if (!(def = virDomainDefParseString(driver->caps, xmlin,
                                            QEMU_EXPECTED_VIRT_TYPES,
                                            VIR_DOMAIN_XML_INACTIVE))) {
            goto endjob;
        }
        if (!virDomainDefCheckABIStability(vm->def, def)) {
            virDomainDefFree(def);
            goto endjob;
        }
        xml = 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;

2943
    /* Shut it down */
2944
    qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED, 0);
2945
    virDomainAuditStop(vm, "saved");
2946 2947 2948
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2949
    if (!vm->persistent) {
2950
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2951
            qemuDomainRemoveInactive(driver, vm);
2952 2953
        vm = NULL;
    }
2954

2955
endjob:
2956
    if (vm) {
2957
        if (ret != 0) {
2958
            if (was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2959
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
2960 2961
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED,
                                          QEMU_ASYNC_JOB_SAVE);
2962
                if (rc < 0) {
2963
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2964 2965 2966 2967
                    event = virDomainEventNewFromObj(vm,
                                                     VIR_DOMAIN_EVENT_SUSPENDED,
                                                     VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
                }
2968
            }
2969
        }
2970
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2971
            vm = NULL;
2972
    }
2973

2974 2975
cleanup:
    VIR_FREE(xml);
2976 2977
    if (event)
        qemuDomainEventQueue(driver, event);
2978
    if (vm)
2979
        virObjectUnlock(vm);
2980
    return ret;
D
Daniel P. Berrange 已提交
2981 2982
}

2983
/* Returns true if a compression program is available in PATH */
2984
static bool qemuCompressProgramAvailable(virQEMUSaveFormat compress)
2985 2986 2987 2988
{
    const char *prog;
    char *c;

2989
    if (compress == QEMU_SAVE_FORMAT_RAW)
2990
        return true;
2991
    prog = qemuSaveCompressionTypeToString(compress);
2992 2993 2994 2995 2996 2997 2998
    c = virFindFileInPath(prog);
    if (!c)
        return false;
    VIR_FREE(c);
    return true;
}

2999 3000 3001
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
3002
{
3003
    virQEMUDriverPtr driver = dom->conn->privateData;
3004
    int compressed;
3005 3006
    int ret = -1;
    virDomainObjPtr vm = NULL;
3007
    virQEMUDriverConfigPtr cfg = NULL;
3008

3009 3010 3011
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
3012

3013
    qemuDriverLock(driver);
3014

3015 3016
    cfg = virQEMUDriverGetConfig(driver);
    if (cfg->saveImageFormat == NULL)
3017
        compressed = QEMU_SAVE_FORMAT_RAW;
3018
    else {
3019
        compressed = qemuSaveCompressionTypeFromString(cfg->saveImageFormat);
3020
        if (compressed < 0) {
3021 3022 3023
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("Invalid save image format specified "
                                   "in configuration file"));
3024
            goto cleanup;
3025
        }
3026
        if (!qemuCompressProgramAvailable(compressed)) {
3027 3028 3029
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("Compression program for image format "
                                   "in configuration file isn't available"));
3030
            goto cleanup;
3031
        }
3032 3033
    }

3034
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
3035 3036 3037
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3038 3039
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
3040 3041 3042
        goto cleanup;
    }

3043
    if (!virDomainObjIsActive(vm)) {
3044 3045
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3046 3047 3048
        goto cleanup;
    }

3049
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
3050
                                 dxml, flags);
3051
    vm = NULL;
3052 3053 3054

cleanup:
    if (vm)
3055
        virObjectUnlock(vm);
3056
    qemuDriverUnlock(driver);
3057
    virObjectUnref(cfg);
3058
    return ret;
3059 3060
}

3061 3062 3063 3064 3065 3066
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

3067
static char *
3068 3069
qemuDomainManagedSavePath(virQEMUDriverPtr driver, virDomainObjPtr vm)
{
3070
    char *ret;
3071
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3072

3073
    if (virAsprintf(&ret, "%s/%s.save", cfg->saveDir, vm->def->name) < 0) {
3074
        virReportOOMError();
3075
        virObjectUnref(cfg);
3076
        return NULL;
3077 3078
    }

3079
    virObjectUnref(cfg);
3080
    return ret;
3081 3082 3083 3084 3085
}

static int
qemuDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
3086 3087
    virQEMUDriverPtr driver;
    virDomainObjPtr vm;
3088 3089 3090 3091
    char *name = NULL;
    int ret = -1;
    int compressed;

3092 3093 3094
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
3095

3096 3097
    if (!(vm = qemuDomObjFromDomainDriver(dom, &driver)))
        return -1;
3098

3099
    if (!virDomainObjIsActive(vm)) {
3100 3101
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3102 3103
        goto cleanup;
    }
3104
    if (!vm->persistent) {
3105 3106
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
3107 3108
        goto cleanup;
    }
3109

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

3113
    VIR_INFO("Saving state to %s", name);
3114

3115
    compressed = QEMU_SAVE_FORMAT_RAW;
3116 3117 3118 3119
    if ((ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
                                      NULL, flags)) == 0)
        vm->hasManagedSave = true;

3120
    vm = NULL;
3121 3122 3123

cleanup:
    if (vm)
3124
        virObjectUnlock(vm);
3125
    qemuDriverUnlock(driver);
3126 3127 3128
    VIR_FREE(name);

    return ret;
3129 3130
}

3131 3132
static int
qemuDomainManagedSaveLoad(virDomainObjPtr vm,
3133 3134
                          void *opaque)
{
3135
    virQEMUDriverPtr driver = opaque;
3136
    char *name;
3137
    int ret = -1;
3138

3139
    virObjectLock(vm);
3140 3141 3142 3143 3144 3145

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

    vm->hasManagedSave = virFileExists(name);

3146
    ret = 0;
3147
cleanup:
3148
    virObjectUnlock(vm);
3149
    VIR_FREE(name);
3150
    return ret;
3151 3152
}

3153

3154 3155 3156 3157
static int
qemuDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
3158
    int ret;
3159

3160
    virCheckFlags(0, -1);
3161

3162 3163
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
3164

3165
    ret = vm->hasManagedSave;
3166
    virObjectUnlock(vm);
3167 3168 3169 3170 3171 3172
    return ret;
}

static int
qemuDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
{
3173 3174
    virQEMUDriverPtr driver;
    virDomainObjPtr vm;
3175 3176 3177
    int ret = -1;
    char *name = NULL;

3178
    virCheckFlags(0, -1);
3179

3180 3181
    if (!(vm = qemuDomObjFromDomainDriver(dom, &driver)))
        return -1;
3182

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

3186 3187 3188 3189 3190 3191 3192
    if (unlink(name) < 0) {
        virReportSystemError(errno,
                             _("Failed to remove managed save file '%s'"),
                             name);
        goto cleanup;
    }

3193
    vm->hasManagedSave = false;
3194
    ret = 0;
3195 3196 3197

cleanup:
    VIR_FREE(name);
3198
    virObjectUnlock(vm);
3199 3200 3201
    qemuDriverUnlock(driver);
    return ret;
}
D
Daniel P. Berrange 已提交
3202

3203
static int qemuDumpToFd(virQEMUDriverPtr driver, virDomainObjPtr vm,
3204 3205 3206 3207 3208
                        int fd, enum qemuDomainAsyncJob asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;

3209
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_DUMP_GUEST_MEMORY)) {
3210 3211
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("dump-guest-memory is not supported"));
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
        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;

3224
    ret = qemuMonitorDumpToFd(priv->mon, fd);
3225 3226 3227 3228 3229
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    return ret;
}

3230
static int
3231
doCoreDump(virQEMUDriverPtr driver,
3232 3233
           virDomainObjPtr vm,
           const char *path,
3234
           virQEMUSaveFormat compress,
3235
           unsigned int dump_flags)
H
Hu Tao 已提交
3236 3237 3238
{
    int fd = -1;
    int ret = -1;
J
Jiri Denemark 已提交
3239
    virFileWrapperFdPtr wrapperFd = NULL;
3240
    int directFlag = 0;
3241
    unsigned int flags = VIR_FILE_WRAPPER_NON_BLOCKING;
H
Hu Tao 已提交
3242 3243

    /* Create an empty file with appropriate ownership.  */
3244
    if (dump_flags & VIR_DUMP_BYPASS_CACHE) {
3245
        flags |= VIR_FILE_WRAPPER_BYPASS_CACHE;
3246 3247
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
3248 3249
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("bypass cache unsupported by this system"));
3250 3251 3252
            goto cleanup;
        }
    }
E
Eric Blake 已提交
3253 3254 3255 3256 3257 3258
    /* 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 已提交
3259 3260
        goto cleanup;

3261
    if (!(wrapperFd = virFileWrapperFdNew(&fd, path, flags)))
3262 3263
        goto cleanup;

3264 3265 3266 3267 3268 3269 3270 3271 3272
    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)
3273 3274
        goto cleanup;

H
Hu Tao 已提交
3275 3276
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
3277
                             _("unable to close file %s"),
H
Hu Tao 已提交
3278 3279 3280
                             path);
        goto cleanup;
    }
J
Jiri Denemark 已提交
3281
    if (virFileWrapperFdClose(wrapperFd) < 0)
3282
        goto cleanup;
H
Hu Tao 已提交
3283

3284
    ret = 0;
H
Hu Tao 已提交
3285 3286

cleanup:
3287
    VIR_FORCE_CLOSE(fd);
3288
    if (ret != 0) {
3289
        virFileWrapperFdCatchError(wrapperFd);
H
Hu Tao 已提交
3290
        unlink(path);
3291 3292
    }
    virFileWrapperFdFree(wrapperFd);
H
Hu Tao 已提交
3293 3294 3295
    return ret;
}

3296
static virQEMUSaveFormat
3297
getCompressionType(virQEMUDriverPtr driver)
3298
{
3299 3300
    int ret = QEMU_SAVE_FORMAT_RAW;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3301

3302 3303 3304 3305
    /*
     * We reuse "save" flag for "dump" here. Then, we can support the same
     * format in "save" and "dump".
     */
3306 3307
    if (cfg->dumpImageFormat) {
        ret = qemuSaveCompressionTypeFromString(cfg->dumpImageFormat);
3308 3309 3310
        /* Use "raw" as the format if the specified format is not valid,
         * or the compress program is not available.
         */
3311
        if (ret < 0) {
3312 3313
            VIR_WARN("%s", _("Invalid dump image format specified in "
                             "configuration file, using raw"));
3314 3315
            ret = QEMU_SAVE_FORMAT_RAW;
            goto cleanup;
3316
        }
3317
        if (!qemuCompressProgramAvailable(ret)) {
3318 3319 3320
            VIR_WARN("%s", _("Compression program for dump image format "
                             "in configuration file isn't available, "
                             "using raw"));
3321 3322
            ret = QEMU_SAVE_FORMAT_RAW;
            goto cleanup;
3323
        }
3324
    }
3325 3326 3327
cleanup:
    virObjectUnref(cfg);
    return ret;
3328 3329
}

3330 3331 3332
static int qemuDomainCoreDump(virDomainPtr dom,
                              const char *path,
                              unsigned int flags)
3333
{
3334
    virQEMUDriverPtr driver = dom->conn->privateData;
3335
    virDomainObjPtr vm;
M
Michal Privoznik 已提交
3336
    qemuDomainObjPrivatePtr priv;
3337
    int resume = 0, paused = 0;
H
Hu Tao 已提交
3338
    int ret = -1;
3339 3340
    virDomainEventPtr event = NULL;

M
Michal Privoznik 已提交
3341
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH |
3342 3343
                  VIR_DUMP_BYPASS_CACHE | VIR_DUMP_RESET |
                  VIR_DUMP_MEMORY_ONLY, -1);
3344

P
Paolo Bonzini 已提交
3345
    qemuDriverLock(driver);
3346
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
P
Paolo Bonzini 已提交
3347 3348 3349 3350

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3351 3352
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
3353 3354 3355
        goto cleanup;
    }

3356 3357
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
3358 3359
        goto cleanup;

D
Daniel P. Berrange 已提交
3360
    if (!virDomainObjIsActive(vm)) {
3361 3362
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3363
        goto endjob;
P
Paolo Bonzini 已提交
3364 3365
    }

P
Paolo Bonzini 已提交
3366 3367
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
3368
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
3369 3370

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
3371 3372
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
3373 3374
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
                                QEMU_ASYNC_JOB_DUMP) < 0)
3375
            goto endjob;
P
Paolo Bonzini 已提交
3376
        paused = 1;
3377 3378

        if (!virDomainObjIsActive(vm)) {
3379 3380
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit"));
3381 3382
            goto endjob;
        }
P
Paolo Bonzini 已提交
3383 3384
    }

3385
    ret = doCoreDump(driver, vm, path, getCompressionType(driver), flags);
3386 3387 3388 3389
    if (ret < 0)
        goto endjob;

    paused = 1;
3390 3391

endjob:
3392
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
3393
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED, 0);
3394
        virDomainAuditStop(vm, "crashed");
3395 3396 3397 3398 3399
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
3400 3401 3402
    /* 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 已提交
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
    else if (((resume && paused) || (flags & VIR_DUMP_RESET)) &&
             virDomainObjIsActive(vm)) {
        if ((ret == 0) && (flags & VIR_DUMP_RESET)) {
            priv =  vm->privateData;
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            ret = qemuMonitorSystemReset(priv->mon);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
        }

        if (resume && qemuProcessStartCPUs(driver, vm, dom->conn,
                                           VIR_DOMAIN_RUNNING_UNPAUSED,
                                           QEMU_ASYNC_JOB_DUMP) < 0) {
3415 3416 3417
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
3418
            if (virGetLastError() == NULL)
3419 3420
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
3421 3422
        }
    }
3423

3424
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3425
        vm = NULL;
3426
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
3427
        qemuDomainRemoveInactive(driver, vm);
3428 3429
        vm = NULL;
    }
3430 3431

cleanup:
P
Paolo Bonzini 已提交
3432
    if (vm)
3433
        virObjectUnlock(vm);
3434 3435
    if (event)
        qemuDomainEventQueue(driver, event);
3436
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
3437 3438 3439
    return ret;
}

3440 3441 3442 3443
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
3444
                     unsigned int flags)
3445
{
3446
    virQEMUDriverPtr driver = dom->conn->privateData;
3447 3448 3449 3450 3451
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;
E
Eric Blake 已提交
3452
    bool unlink_tmp = false;
3453
    virQEMUDriverConfigPtr cfg = NULL;
3454

E
Eric Blake 已提交
3455 3456
    virCheckFlags(0, NULL);

3457
    if (!(vm = qemuDomObjFromDomain(dom)))
3458 3459 3460
        goto cleanup;

    priv = vm->privateData;
3461
    cfg = virQEMUDriverGetConfig(driver);
3462

3463
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
3464 3465 3466
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
3467 3468
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3469 3470 3471 3472 3473 3474
        goto endjob;
    }

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

3481
    if (virAsprintf(&tmp, "%s/qemu.screendump.XXXXXX", cfg->cacheDir) < 0) {
3482 3483 3484 3485
        virReportOOMError();
        goto endjob;
    }

3486 3487
    if ((tmp_fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
        virReportSystemError(errno, _("mkostemp(\"%s\") failed"), tmp);
3488 3489
        goto endjob;
    }
E
Eric Blake 已提交
3490
    unlink_tmp = true;
3491

3492
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
3493

3494
    qemuDomainObjEnterMonitor(driver, vm);
3495
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
3496
        qemuDomainObjExitMonitor(driver, vm);
3497 3498
        goto endjob;
    }
3499
    qemuDomainObjExitMonitor(driver, vm);
3500 3501 3502 3503 3504 3505

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

E
Eric Blake 已提交
3506
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
3507 3508
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("unable to open stream"));
3509 3510 3511 3512 3513 3514 3515
        goto endjob;
    }

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

endjob:
    VIR_FORCE_CLOSE(tmp_fd);
E
Eric Blake 已提交
3516 3517
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
3518
    VIR_FREE(tmp);
3519

3520
    if (qemuDomainObjEndJob(driver, vm) == 0)
3521 3522 3523 3524
        vm = NULL;

cleanup:
    if (vm)
3525
        virObjectUnlock(vm);
3526
    virObjectUnref(cfg);
3527 3528 3529
    return ret;
}

H
Hu Tao 已提交
3530 3531 3532
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
3533
    struct qemuDomainWatchdogEvent *wdEvent = data;
3534
    virQEMUDriverPtr driver = opaque;
3535
    virQEMUDriverConfigPtr cfg;
H
Hu Tao 已提交
3536

W
Wen Congyang 已提交
3537
    qemuDriverLock(driver);
3538
    virObjectLock(wdEvent->vm);
3539
    cfg = virQEMUDriverGetConfig(driver);
W
Wen Congyang 已提交
3540

H
Hu Tao 已提交
3541 3542 3543 3544
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;
3545
            unsigned int flags = 0;
H
Hu Tao 已提交
3546

E
Eric Blake 已提交
3547
            if (virAsprintf(&dumpfile, "%s/%s-%u",
3548
                            cfg->autoDumpPath,
H
Hu Tao 已提交
3549
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
3550 3551
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
3552
                goto unlock;
E
Eric Blake 已提交
3553
            }
H
Hu Tao 已提交
3554

3555 3556
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
3557 3558 3559
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
3560 3561

            if (!virDomainObjIsActive(wdEvent->vm)) {
3562 3563
                virReportError(VIR_ERR_OPERATION_INVALID,
                               "%s", _("domain is not running"));
W
Wen Congyang 已提交
3564 3565
                VIR_FREE(dumpfile);
                goto endjob;
H
Hu Tao 已提交
3566 3567
            }

3568
            flags |= cfg->autoDumpBypassCache ? VIR_DUMP_BYPASS_CACHE: 0;
3569
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
3570
                             getCompressionType(driver), flags);
H
Hu Tao 已提交
3571
            if (ret < 0)
3572 3573
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("Dump failed"));
H
Hu Tao 已提交
3574

J
Jiri Denemark 已提交
3575
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
3576 3577
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
3578 3579

            if (ret < 0)
3580 3581
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("Resuming after dump failed"));
H
Hu Tao 已提交
3582 3583 3584 3585

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3586 3587
    default:
        goto unlock;
H
Hu Tao 已提交
3588 3589
    }

W
Wen Congyang 已提交
3590 3591 3592 3593
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3594
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3595 3596

unlock:
3597
    virObjectUnlock(wdEvent->vm);
3598
    virObjectUnref(wdEvent->vm);
W
Wen Congyang 已提交
3599
    qemuDriverUnlock(driver);
H
Hu Tao 已提交
3600
    VIR_FREE(wdEvent);
3601
    virObjectUnref(cfg);
H
Hu Tao 已提交
3602
}
P
Paolo Bonzini 已提交
3603

3604
static int qemuDomainHotplugVcpus(virQEMUDriverPtr driver,
3605 3606
                                  virDomainObjPtr vm,
                                  unsigned int nvcpus)
3607 3608
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3609
    int i, rc = 1;
3610
    int ret = -1;
3611
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3612
    int vcpus = oldvcpus;
3613 3614
    pid_t *cpupids = NULL;
    int ncpupids;
3615 3616
    virCgroupPtr cgroup = NULL;
    virCgroupPtr cgroup_vcpu = NULL;
3617
    bool cgroup_available = false;
3618

3619
    qemuDomainObjEnterMonitor(driver, vm);
3620

3621 3622 3623
    /* 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 已提交
3624 3625
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
3626 3627 3628 3629 3630 3631 3632
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3633
            vcpus++;
3634 3635
        }
    } else {
E
Eric Blake 已提交
3636
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
3637 3638 3639 3640 3641 3642 3643
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3644
            vcpus--;
3645 3646 3647
        }
    }

3648 3649
    /* hotplug succeeded */

3650 3651
    ret = 0;

3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
    /* 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;
    }

3662 3663 3664 3665 3666 3667 3668 3669 3670
    /* 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;
    }

3671
    if (ncpupids != vcpus) {
3672 3673 3674 3675
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("got wrong number of vCPU pids from QEMU monitor. "
                         "got %d, wanted %d"),
                       ncpupids, vcpus);
3676 3677 3678 3679
        ret = -1;
        goto cleanup;
    }

3680 3681
    cgroup_available = (virCgroupForDomain(driver->cgroup, vm->def->name,
                                           &cgroup, 0) == 0);
3682

3683 3684 3685 3686
    if (nvcpus > oldvcpus) {
        for (i = oldvcpus; i < nvcpus; i++) {
            if (cgroup_available) {
                int rv = -1;
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705
                /* Create cgroup for the onlined vcpu */
                rv = virCgroupForVcpu(cgroup, i, &cgroup_vcpu, 1);
                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;
                }
3706
            }
3707

3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
            /* 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;

                if (cgroup_available) {
                    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 {
3742 3743
                    if (virProcessSetAffinity(cpupids[i],
                                              vcpupin->cpumask) < 0) {
3744 3745 3746 3747 3748 3749 3750
                        virReportError(VIR_ERR_SYSTEM_ERROR,
                                       _("failed to set cpu affinity for vcpu %d"),
                                       i);
                        ret = -1;
                        goto cleanup;
                    }
                }
3751
            }
3752 3753

            virCgroupFree(&cgroup_vcpu);
G
Guido Günther 已提交
3754
        }
3755 3756 3757 3758 3759 3760 3761
    } else {
        for (i = oldvcpus - 1; i >= nvcpus; i--) {
            virDomainVcpuPinDefPtr vcpupin = NULL;

            if (cgroup_available) {
                int rv = -1;

3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
                rv = virCgroupForVcpu(cgroup, i, &cgroup_vcpu, 0);
                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);
            }

3776 3777 3778 3779 3780
            /* Free vcpupin setting */
            if ((vcpupin = virDomainLookupVcpuPin(vm->def, i))) {
                VIR_FREE(vcpupin);
            }
        }
3781 3782
    }

3783 3784 3785 3786 3787
    priv->nvcpupids = ncpupids;
    VIR_FREE(priv->vcpupids);
    priv->vcpupids = cpupids;
    cpupids = NULL;

3788
cleanup:
3789
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3790
    vm->def->vcpus = vcpus;
3791
    VIR_FREE(cpupids);
3792
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3793 3794 3795 3796
    if (cgroup)
        virCgroupFree(&cgroup);
    if (cgroup_vcpu)
        virCgroupFree(&cgroup_vcpu);
3797 3798 3799
    return ret;

unsupported:
3800 3801
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("cannot change vcpu count of this domain"));
3802 3803 3804 3805
    goto cleanup;
}


3806
static int
3807 3808
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3809
{
3810
    virQEMUDriverPtr driver = dom->conn->privateData;
3811
    virDomainObjPtr vm;
3812
    virDomainDefPtr persistentDef;
3813 3814
    const char * type;
    int max;
3815
    int ret = -1;
3816
    bool maximum;
3817
    virQEMUDriverConfigPtr cfg = NULL;
3818

3819 3820
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3821 3822 3823
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
3824 3825
        virReportError(VIR_ERR_INVALID_ARG,
                       _("argument out of range: %d"), nvcpus);
3826 3827 3828
        return -1;
    }

3829 3830
    cfg = virQEMUDriverGetConfig(driver);

3831
    if (!(vm = qemuDomObjFromDomain(dom)))
3832
        goto cleanup;
3833

3834
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
3835 3836
        goto cleanup;

3837 3838 3839
    maximum = (flags & VIR_DOMAIN_VCPU_MAXIMUM) != 0;
    flags &= ~VIR_DOMAIN_VCPU_MAXIMUM;

3840 3841 3842
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto endjob;
3843 3844 3845

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

3851
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
3852 3853 3854
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown virt type in domain definition '%d'"),
                       vm->def->virtType);
3855 3856 3857
        goto endjob;
    }

3858
    if ((max = qemuGetMaxVCPUs(NULL, type)) < 0) {
3859 3860
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
3861 3862 3863
        goto endjob;
    }

3864
    if (!maximum && vm->def->maxvcpus < max) {
3865 3866 3867
        max = vm->def->maxvcpus;
    }

3868
    if (nvcpus > max) {
3869 3870 3871
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
3872 3873 3874
        goto endjob;
    }

3875
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3876
        if (qemuDomainHotplugVcpus(driver, vm, nvcpus) < 0)
3877 3878 3879 3880
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
3881 3882 3883 3884 3885 3886 3887
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3888

3889
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
3890
            goto endjob;
3891
    }
3892

3893
    ret = 0;
3894

3895
endjob:
3896
    if (qemuDomainObjEndJob(driver, vm) == 0)
3897
        vm = NULL;
3898

3899
cleanup:
3900
    if (vm)
3901
        virObjectUnlock(vm);
3902
    virObjectUnref(cfg);
3903
    return ret;
3904 3905
}

3906
static int
3907
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3908
{
3909
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3910 3911
}

3912 3913

static int
3914 3915 3916 3917 3918
qemuDomainPinVcpuFlags(virDomainPtr dom,
                       unsigned int vcpu,
                       unsigned char *cpumap,
                       int maplen,
                       unsigned int flags) {
3919

3920
    virQEMUDriverPtr driver = dom->conn->privateData;
3921
    virDomainObjPtr vm;
3922
    virDomainDefPtr persistentDef = NULL;
3923 3924
    virCgroupPtr cgroup_dom = NULL;
    virCgroupPtr cgroup_vcpu = NULL;
3925
    int ret = -1;
3926
    qemuDomainObjPrivatePtr priv;
3927
    bool doReset = false;
3928 3929
    int newVcpuPinNum = 0;
    virDomainVcpuPinDefPtr *newVcpuPin = NULL;
3930
    virBitmapPtr pcpumap = NULL;
3931
    virQEMUDriverConfigPtr cfg = NULL;
3932

3933 3934 3935
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

3936 3937
    cfg = virQEMUDriverGetConfig(driver);

3938
    if (!(vm = qemuDomObjFromDomain(dom)))
3939 3940
        goto cleanup;

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

3945 3946 3947
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3948 3949 3950
        virReportError(VIR_ERR_INVALID_ARG,
                       _("vcpu number out of range %d > %d"),
                       vcpu, priv->nvcpupids);
3951
        goto cleanup;
3952 3953
    }

3954 3955 3956 3957
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
        goto cleanup;

3958 3959 3960
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
3961 3962
    if (virBitmapIsAllSet(pcpumap))
        doReset = true;
3963

3964
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3965

3966
        if (priv->vcpupids == NULL) {
3967 3968
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cpu affinity is not supported"));
3969 3970 3971
            goto cleanup;
        }

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

3987
        if (virDomainVcpuPinAdd(&newVcpuPin, &newVcpuPinNum, cpumap, maplen, vcpu) < 0) {
3988 3989
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to update vcpupin"));
H
Hu Tao 已提交
3990
            virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
            goto cleanup;
        }

        /* Configure the corresponding cpuset cgroup before set affinity. */
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUSET)) {
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup_dom, 0) == 0 &&
                virCgroupForVcpu(cgroup_dom, vcpu, &cgroup_vcpu, 0) == 0 &&
                qemuSetupCgroupVcpuPin(cgroup_vcpu, newVcpuPin, newVcpuPinNum, vcpu) < 0) {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("failed to set cpuset.cpus in cgroup"
                                 " for vcpu %d"), vcpu);
4002 4003 4004
                goto cleanup;
            }
        } else {
4005
            if (virProcessSetAffinity(priv->vcpupids[vcpu], pcpumap) < 0) {
4006 4007 4008 4009
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("failed to set cpu affinity for vcpu %d"),
                               vcpu);
                goto cleanup;
H
Hu Tao 已提交
4010
            }
4011 4012
        }

4013
        if (doReset) {
4014
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
4015
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4016
                               _("failed to delete vcpupin xml of "
4017
                                 "a running domain"));
4018 4019
                goto cleanup;
            }
4020 4021
        } else {
            if (vm->def->cputune.vcpupin)
H
Hu Tao 已提交
4022
                virDomainVcpuPinDefArrayFree(vm->def->cputune.vcpupin, vm->def->cputune.nvcpupin);
4023 4024 4025 4026

            vm->def->cputune.vcpupin = newVcpuPin;
            vm->def->cputune.nvcpupin = newVcpuPinNum;
            newVcpuPin = NULL;
4027 4028
        }

4029
        if (newVcpuPin)
H
Hu Tao 已提交
4030
            virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
4031

4032
        if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0)
4033
            goto cleanup;
4034
    }
4035

4036 4037
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

4038
        if (doReset) {
E
Eric Blake 已提交
4039
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
4040 4041 4042
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to delete vcpupin xml of "
                                 "a persistent domain"));
4043 4044 4045
                goto cleanup;
            }
        } else {
H
Hu Tao 已提交
4046 4047 4048 4049 4050 4051 4052
            if (!persistentDef->cputune.vcpupin) {
                if (VIR_ALLOC(persistentDef->cputune.vcpupin) < 0) {
                    virReportOOMError();
                    goto cleanup;
                }
                persistentDef->cputune.nvcpupin = 0;
            }
4053
            if (virDomainVcpuPinAdd(&persistentDef->cputune.vcpupin,
H
Hu Tao 已提交
4054 4055 4056 4057
                                    &persistentDef->cputune.nvcpupin,
                                    cpumap,
                                    maplen,
                                    vcpu) < 0) {
4058 4059 4060
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to update or add vcpupin xml of "
                                 "a persistent domain"));
4061 4062
                goto cleanup;
            }
4063
        }
4064

4065
        ret = virDomainSaveConfig(cfg->configDir, persistentDef);
4066 4067 4068
        goto cleanup;
    }

4069
    ret = 0;
4070

4071
cleanup:
4072 4073 4074 4075
    if (cgroup_vcpu)
        virCgroupFree(&cgroup_vcpu);
    if (cgroup_dom)
        virCgroupFree(&cgroup_dom);
4076
    if (vm)
4077
        virObjectUnlock(vm);
4078
    virBitmapFree(pcpumap);
4079
    virObjectUnref(cfg);
4080
    return ret;
4081 4082
}

4083
static int
4084
qemuDomainPinVcpu(virDomainPtr dom,
4085 4086 4087
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
4088 4089
    return qemuDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                  VIR_DOMAIN_AFFECT_LIVE);
4090 4091
}

4092
static int
4093 4094 4095 4096 4097
qemuDomainGetVcpuPinInfo(virDomainPtr dom,
                         int ncpumaps,
                         unsigned char *cpumaps,
                         int maplen,
                         unsigned int flags) {
4098

4099
    virQEMUDriverPtr driver = dom->conn->privateData;
E
Eric Blake 已提交
4100
    virDomainObjPtr vm = NULL;
4101 4102 4103 4104
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
4105
    virDomainVcpuPinDefPtr *vcpupin_list;
H
Hu Tao 已提交
4106
    virBitmapPtr cpumask = NULL;
4107
    unsigned char *cpumap;
H
Hu Tao 已提交
4108
    bool pinned;
4109 4110 4111 4112

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4113
    if (!(vm = qemuDomObjFromDomain(dom)))
4114 4115
        goto cleanup;

4116 4117 4118
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &targetDef) < 0)
        goto cleanup;
4119 4120 4121 4122 4123

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

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

4127
    if ((hostcpus = nodeGetCPUCount()) < 0)
4128
        goto cleanup;
4129

4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
    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 已提交
4158 4159 4160
            if (virBitmapGetBit(cpumask, pcpu, &pinned) < 0)
                goto cleanup;
            if (!pinned)
4161 4162 4163 4164 4165 4166 4167
                VIR_UNUSE_CPU(cpumap, pcpu);
        }
    }
    ret = ncpumaps;

cleanup:
    if (vm)
4168
        virObjectUnlock(vm);
4169 4170 4171
    return ret;
}

H
Hu Tao 已提交
4172
static int
4173 4174 4175 4176
qemuDomainPinEmulator(virDomainPtr dom,
                      unsigned char *cpumap,
                      int maplen,
                      unsigned int flags)
H
Hu Tao 已提交
4177
{
4178
    virQEMUDriverPtr driver = dom->conn->privateData;
H
Hu Tao 已提交
4179 4180 4181 4182 4183 4184 4185
    virDomainObjPtr vm;
    virCgroupPtr cgroup_dom = NULL;
    virCgroupPtr cgroup_emulator = NULL;
    pid_t pid;
    virDomainDefPtr persistentDef = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
4186
    bool doReset = false;
H
Hu Tao 已提交
4187 4188
    int newVcpuPinNum = 0;
    virDomainVcpuPinDefPtr *newVcpuPin = NULL;
4189
    virBitmapPtr pcpumap = NULL;
4190
    virQEMUDriverConfigPtr cfg = NULL;
H
Hu Tao 已提交
4191 4192 4193 4194

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4195 4196
    cfg = virQEMUDriverGetConfig(driver);

4197
    if (!(vm = qemuDomObjFromDomain(dom)))
H
Hu Tao 已提交
4198 4199
        goto cleanup;

4200 4201 4202 4203 4204 4205 4206
    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;
    }

H
Hu Tao 已提交
4207 4208 4209 4210 4211 4212
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    priv = vm->privateData;

4213 4214 4215 4216
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
        goto cleanup;

H
Hu Tao 已提交
4217 4218 4219
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
4220 4221
    if (virBitmapIsAllSet(pcpumap))
        doReset = true;
H
Hu Tao 已提交
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232

    pid = vm->pid;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {

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

4233
            if (virDomainVcpuPinAdd(&newVcpuPin, &newVcpuPinNum, cpumap, maplen, -1) < 0) {
H
Hu Tao 已提交
4234 4235
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to update vcpupin"));
H
Hu Tao 已提交
4236
                virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
H
Hu Tao 已提交
4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248
                goto cleanup;
            }

            if (qemuCgroupControllerActive(driver,
                                           VIR_CGROUP_CONTROLLER_CPUSET)) {
                /*
                 * Configure the corresponding cpuset cgroup.
                 * If no cgroup for domain or hypervisor exists, do nothing.
                 */
                if (virCgroupForDomain(driver->cgroup, vm->def->name,
                                       &cgroup_dom, 0) == 0) {
                    if (virCgroupForEmulator(cgroup_dom, &cgroup_emulator, 0) == 0) {
4249 4250
                        if (qemuSetupCgroupEmulatorPin(cgroup_emulator,
                                                       newVcpuPin[0]->cpumask) < 0) {
H
Hu Tao 已提交
4251 4252 4253 4254 4255 4256 4257 4258
                            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                           _("failed to set cpuset.cpus in cgroup"
                                             " for emulator threads"));
                            goto cleanup;
                        }
                    }
                }
            } else {
4259
                if (virProcessSetAffinity(pid, pcpumap) < 0) {
H
Hu Tao 已提交
4260 4261 4262 4263 4264 4265 4266
                    virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                                   _("failed to set cpu affinity for "
                                     "emulator threads"));
                    goto cleanup;
                }
            }

4267
            if (doReset) {
H
Hu Tao 已提交
4268 4269 4270 4271 4272 4273 4274
                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 已提交
4275
                virDomainVcpuPinDefFree(vm->def->cputune.emulatorpin);
H
Hu Tao 已提交
4276 4277 4278 4279 4280
                vm->def->cputune.emulatorpin = newVcpuPin[0];
                VIR_FREE(newVcpuPin);
            }

            if (newVcpuPin)
H
Hu Tao 已提交
4281
                virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
H
Hu Tao 已提交
4282 4283 4284 4285 4286 4287
        } else {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cpu affinity is not supported"));
            goto cleanup;
        }

4288
        if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0)
H
Hu Tao 已提交
4289 4290 4291 4292 4293
            goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

4294
        if (doReset) {
H
Hu Tao 已提交
4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309
            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;
            }
        }

4310
        ret = virDomainSaveConfig(cfg->configDir, persistentDef);
H
Hu Tao 已提交
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (cgroup_emulator)
        virCgroupFree(&cgroup_emulator);
    if (cgroup_dom)
        virCgroupFree(&cgroup_dom);
4321
    virBitmapFree(pcpumap);
H
Hu Tao 已提交
4322 4323

    if (vm)
4324
        virObjectUnlock(vm);
4325
    virObjectUnref(cfg);
H
Hu Tao 已提交
4326 4327 4328 4329
    return ret;
}

static int
4330 4331 4332 4333
qemuDomainGetEmulatorPinInfo(virDomainPtr dom,
                             unsigned char *cpumaps,
                             int maplen,
                             unsigned int flags)
H
Hu Tao 已提交
4334
{
4335
    virQEMUDriverPtr driver = dom->conn->privateData;
H
Hu Tao 已提交
4336 4337 4338 4339
    virDomainObjPtr vm = NULL;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    int maxcpu, hostcpus, pcpu;
H
Hu Tao 已提交
4340 4341
    virBitmapPtr cpumask = NULL;
    bool pinned;
H
Hu Tao 已提交
4342 4343 4344 4345

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4346
    if (!(vm = qemuDomObjFromDomain(dom)))
H
Hu Tao 已提交
4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358
        goto cleanup;

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &targetDef) < 0)
        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);

4359
    if ((hostcpus = nodeGetCPUCount()) < 0)
H
Hu Tao 已提交
4360
        goto cleanup;
4361

H
Hu Tao 已提交
4362 4363 4364 4365 4366 4367 4368 4369 4370 4371
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

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

4372 4373 4374 4375 4376
    if (targetDef->cputune.emulatorpin) {
        cpumask = targetDef->cputune.emulatorpin->cpumask;
    } else if (targetDef->cpumask) {
        cpumask = targetDef->cpumask;
    } else {
H
Hu Tao 已提交
4377 4378 4379 4380 4381
        ret = 0;
        goto cleanup;
    }

    for (pcpu = 0; pcpu < maxcpu; pcpu++) {
H
Hu Tao 已提交
4382 4383 4384
        if (virBitmapGetBit(cpumask, pcpu, &pinned) < 0)
            goto cleanup;
        if (!pinned)
H
Hu Tao 已提交
4385 4386 4387 4388 4389 4390 4391
            VIR_UNUSE_CPU(cpumaps, pcpu);
    }

    ret = 1;

cleanup:
    if (vm)
4392
        virObjectUnlock(vm);
H
Hu Tao 已提交
4393 4394 4395
    return ret;
}

4396
static int
4397 4398 4399 4400 4401
qemuDomainGetVcpus(virDomainPtr dom,
                   virVcpuInfoPtr info,
                   int maxinfo,
                   unsigned char *cpumaps,
                   int maplen) {
4402
    virDomainObjPtr vm;
4403
    int i, v, maxcpu, hostcpus;
4404
    int ret = -1;
4405
    qemuDomainObjPrivatePtr priv;
4406

4407
    if (!(vm = qemuDomObjFromDomain(dom)))
4408 4409
        goto cleanup;

D
Daniel P. Berrange 已提交
4410
    if (!virDomainObjIsActive(vm)) {
4411 4412 4413
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s",
                       _("cannot list vcpu pinning for an inactive domain"));
4414
        goto cleanup;
4415 4416
    }

4417 4418
    priv = vm->privateData;

4419
    if ((hostcpus = nodeGetCPUCount()) < 0)
4420
        goto cleanup;
4421 4422

    maxcpu = maplen * 8;
4423 4424
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
4425 4426

    /* Clamp to actual number of vcpus */
4427 4428
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
4429

4430 4431 4432 4433 4434 4435
    if (maxinfo >= 1) {
        if (info != NULL) {
            memset(info, 0, sizeof(*info) * maxinfo);
            for (i = 0 ; i < maxinfo ; i++) {
                info[i].number = i;
                info[i].state = VIR_VCPU_RUNNING;
4436

4437
                if (priv->vcpupids != NULL &&
4438 4439 4440 4441 4442
                    qemuGetProcessInfo(&(info[i].cpuTime),
                                       &(info[i].cpu),
                                       NULL,
                                       vm->pid,
                                       priv->vcpupids[i]) < 0) {
4443
                    virReportSystemError(errno, "%s",
4444 4445 4446
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
4447
            }
4448 4449
        }

4450 4451
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
4452
            if (priv->vcpupids != NULL) {
4453 4454
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);
4455 4456 4457
                    virBitmapPtr map = NULL;
                    unsigned char *tmpmap = NULL;
                    int tmpmapLen = 0;
4458

4459 4460
                    if (virProcessGetAffinity(priv->vcpupids[v],
                                              &map, maxcpu) < 0)
4461
                        goto cleanup;
4462 4463 4464 4465 4466 4467 4468
                    virBitmapToData(map, &tmpmap, &tmpmapLen);
                    if (tmpmapLen > maplen)
                        tmpmapLen = maplen;
                    memcpy(cpumap, tmpmap, tmpmapLen);

                    VIR_FREE(tmpmap);
                    virBitmapFree(map);
4469
                }
4470
            } else {
4471 4472
                virReportError(VIR_ERR_OPERATION_INVALID,
                               "%s", _("cpu affinity is not available"));
4473
                goto cleanup;
4474 4475 4476
            }
        }
    }
4477
    ret = maxinfo;
4478

4479
cleanup:
4480
    if (vm)
4481
        virObjectUnlock(vm);
4482
    return ret;
4483 4484 4485
}


4486
static int
4487
qemuDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
4488
{
4489
    virQEMUDriverPtr driver = dom->conn->privateData;
4490
    virDomainObjPtr vm;
4491
    virDomainDefPtr def;
4492
    int ret = -1;
4493

4494 4495
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
4496 4497
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

4498
    if (!(vm = qemuDomObjFromDomain(dom)))
4499
        goto cleanup;
4500

4501 4502
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags, &def) < 0)
        goto cleanup;
4503

4504
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
4505
        def = vm->def;
4506 4507
    }

4508
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
4509

4510
cleanup:
4511
    if (vm)
4512
        virObjectUnlock(vm);
4513 4514 4515
    return ret;
}

4516
static int
4517
qemuDomainGetMaxVcpus(virDomainPtr dom)
4518
{
4519 4520
    return qemuDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
                                         VIR_DOMAIN_VCPU_MAXIMUM));
4521 4522
}

4523
static int qemuDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
4524
{
4525
    virQEMUDriverPtr driver = dom->conn->privateData;
4526 4527 4528 4529
    virDomainObjPtr vm;
    int ret = -1;

    qemuDriverLock(driver);
4530
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4531

4532 4533
    memset(seclabel, 0, sizeof(*seclabel));

4534 4535 4536
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4537 4538
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
4539 4540 4541
        goto cleanup;
    }

4542
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
4543 4544 4545
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown virt type in domain definition '%d'"),
                       vm->def->virtType);
4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562
        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 已提交
4563
    if (virDomainObjIsActive(vm)) {
4564
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
4565
                                              vm->def, vm->pid, seclabel) < 0) {
4566 4567
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to get security label"));
4568
            goto cleanup;
4569 4570 4571 4572 4573 4574 4575
        }
    }

    ret = 0;

cleanup:
    if (vm)
4576
        virObjectUnlock(vm);
4577
    qemuDriverUnlock(driver);
4578 4579 4580
    return ret;
}

M
Marcelo Cerri 已提交
4581 4582 4583
static int qemuDomainGetSecurityLabelList(virDomainPtr dom,
                                          virSecurityLabelPtr* seclabels)
{
4584
    virQEMUDriverPtr driver = dom->conn->privateData;
M
Marcelo Cerri 已提交
4585 4586 4587 4588 4589
    virDomainObjPtr vm;
    int i, ret = -1;

    /* Protect domain data with qemu lock */
    qemuDriverLock(driver);
4590
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
M
Marcelo Cerri 已提交
4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607

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

    if (!virDomainVirtTypeToString(vm->def->virtType)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown virt type in domain definition '%d'"),
                       vm->def->virtType);
        goto cleanup;
    }

    /*
4608
     * Check the comment in qemuDomainGetSecurityLabel function.
M
Marcelo Cerri 已提交
4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648
     */
    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)
4649
        virObjectUnlock(vm);
M
Marcelo Cerri 已提交
4650 4651 4652
    qemuDriverUnlock(driver);
    return ret;
}
4653 4654
static int qemuNodeGetSecurityModel(virConnectPtr conn,
                                    virSecurityModelPtr secmodel)
4655
{
4656
    virQEMUDriverPtr driver = conn->privateData;
4657
    char *p;
4658
    int ret = 0;
4659

4660
    qemuDriverLock(driver);
4661 4662
    memset(secmodel, 0, sizeof(*secmodel));

4663 4664 4665
    /* We treat no driver as success, but simply return no data in *secmodel */
    if (driver->caps->host.nsecModels == 0 ||
        driver->caps->host.secModels[0].model == NULL)
4666
        goto cleanup;
4667

4668
    p = driver->caps->host.secModels[0].model;
4669
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
4670 4671 4672
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security model string exceeds max %d bytes"),
                       VIR_SECURITY_MODEL_BUFLEN-1);
4673 4674
        ret = -1;
        goto cleanup;
4675 4676 4677
    }
    strcpy(secmodel->model, p);

4678
    p = driver->caps->host.secModels[0].doi;
4679
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
4680 4681 4682
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security DOI string exceeds max %d bytes"),
                       VIR_SECURITY_DOI_BUFLEN-1);
4683 4684
        ret = -1;
        goto cleanup;
4685 4686
    }
    strcpy(secmodel->doi, p);
4687 4688 4689 4690

cleanup:
    qemuDriverUnlock(driver);
    return ret;
4691 4692
}

E
Eric Blake 已提交
4693
/* Return -1 on most failures after raising error, -2 if edit was specified
4694 4695 4696
 * 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.  */
4697
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
4698
qemuDomainSaveImageOpen(virQEMUDriverPtr driver,
4699 4700
                        const char *path,
                        virDomainDefPtr *ret_def,
4701
                        virQEMUSaveHeaderPtr ret_header,
J
Jiri Denemark 已提交
4702 4703
                        bool bypass_cache,
                        virFileWrapperFdPtr *wrapperFd,
4704 4705
                        const char *xmlin, int state, bool edit,
                        bool unlink_corrupt)
J
Jiri Denemark 已提交
4706
{
W
Wen Congyang 已提交
4707
    int fd = -1;
4708
    virQEMUSaveHeader header;
J
Jiri Denemark 已提交
4709 4710
    char *xml = NULL;
    virDomainDefPtr def = NULL;
4711
    int oflags = edit ? O_RDWR : O_RDONLY;
4712

4713
    if (bypass_cache) {
4714
        int directFlag = virFileDirectFdFlag();
4715
        if (directFlag < 0) {
4716 4717
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("bypass cache unsupported by this system"));
4718 4719
            goto error;
        }
4720
        oflags |= directFlag;
4721
    }
4722

E
Eric Blake 已提交
4723 4724
    if ((fd = qemuOpenFile(driver, path, oflags, NULL, NULL)) < 0)
        goto error;
J
Jiri Denemark 已提交
4725 4726 4727
    if (bypass_cache &&
        !(*wrapperFd = virFileWrapperFdNew(&fd, path,
                                           VIR_FILE_WRAPPER_BYPASS_CACHE)))
4728
        goto error;
4729 4730

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
4731 4732 4733 4734 4735 4736 4737 4738 4739
        if (unlink_corrupt) {
            if (VIR_CLOSE(fd) < 0 || unlink(path) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove corrupt file: %s"),
                                     path);
                goto error;
            }
            return -3;
        }
4740 4741
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
4742
        goto error;
4743 4744
    }

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

4748
        if (memcmp(header.magic, QEMU_SAVE_PARTIAL,
E
Eric Blake 已提交
4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760
                   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;
            }
        }
4761
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", msg);
J
Jiri Denemark 已提交
4762
        goto error;
4763 4764
    }

4765
    if (header.version > QEMU_SAVE_VERSION) {
4766 4767 4768 4769
        /* convert endianess and try again */
        bswap_header(&header);
    }

4770
    if (header.version > QEMU_SAVE_VERSION) {
4771 4772
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
4773
                       header.version, QEMU_SAVE_VERSION);
J
Jiri Denemark 已提交
4774
        goto error;
4775 4776
    }

4777
    if (header.xml_len <= 0) {
4778 4779
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
4780
        goto error;
4781 4782
    }

4783 4784
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
4785
        goto error;
4786 4787 4788
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
4789 4790
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
4791
        goto error;
4792 4793
    }

4794 4795
    if (edit && STREQ(xml, xmlin) &&
        (state < 0 || state == header.was_running)) {
4796 4797 4798 4799 4800 4801 4802
        VIR_FREE(xml);
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("cannot close file: %s"), path);
            goto error;
        }
        return -2;
    }
4803 4804
    if (state >= 0)
        header.was_running = state;
4805

4806
    /* Create a domain from this XML */
4807
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4808
                                        QEMU_EXPECTED_VIRT_TYPES,
4809
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
4810
        goto error;
4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824
    if (xmlin) {
        virDomainDefPtr def2 = NULL;

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

J
Jiri Denemark 已提交
4826
    VIR_FREE(xml);
4827

J
Jiri Denemark 已提交
4828 4829
    *ret_def = def;
    *ret_header = header;
4830

J
Jiri Denemark 已提交
4831
    return fd;
4832

J
Jiri Denemark 已提交
4833 4834 4835
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
4836
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
4837 4838 4839 4840

    return -1;
}

4841 4842
static int ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5) ATTRIBUTE_NONNULL(6)
qemuDomainSaveImageStartVM(virConnectPtr conn,
4843
                           virQEMUDriverPtr driver,
4844 4845
                           virDomainObjPtr vm,
                           int *fd,
4846
                           const virQEMUSaveHeaderPtr header,
4847 4848
                           const char *path,
                           bool start_paused)
J
Jiri Denemark 已提交
4849 4850 4851 4852
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
4853
    virCommandPtr cmd = NULL;
4854
    char *errbuf = NULL;
4855
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
J
Jiri Denemark 已提交
4856 4857

    if (header->version == 2) {
4858
        const char *prog = qemuSaveCompressionTypeToString(header->compressed);
4859
        if (prog == NULL) {
4860 4861 4862
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("Invalid compressed save format %d"),
                           header->compressed);
J
Jiri Denemark 已提交
4863
            goto out;
4864
        }
4865

4866
        if (header->compressed != QEMU_SAVE_FORMAT_RAW) {
4867
            cmd = virCommandNewArgList(prog, "-dc", NULL);
4868 4869
            intermediatefd = *fd;
            *fd = -1;
4870 4871 4872

            virCommandSetInputFD(cmd, intermediatefd);
            virCommandSetOutputFD(cmd, fd);
4873 4874
            virCommandSetErrorBuffer(cmd, &errbuf);
            virCommandDoAsyncIO(cmd);
4875 4876

            if (virCommandRunAsync(cmd, NULL) < 0) {
4877 4878 4879
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to start decompression binary %s"),
                               prog);
4880
                *fd = intermediatefd;
J
Jiri Denemark 已提交
4881
                goto out;
4882 4883 4884
            }
        }
    }
J
Jiri Denemark 已提交
4885

4886
    /* Set the migration source and start it up. */
4887 4888 4889
    ret = qemuProcessStart(conn, driver, vm, "stdio", *fd, path, NULL,
                           VIR_NETDEV_VPORT_PROFILE_OP_RESTORE,
                           VIR_QEMU_PROCESS_START_PAUSED);
J
Jiri Denemark 已提交
4890

4891
    if (intermediatefd != -1) {
4892
        if (ret < 0) {
4893 4894 4895
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
4896 4897
             */
            VIR_FORCE_CLOSE(intermediatefd);
4898
            VIR_FORCE_CLOSE(*fd);
4899 4900
        }

4901 4902
        if (virCommandWait(cmd, NULL) < 0) {
            qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED, 0);
4903
            ret = -1;
4904
        }
4905
        VIR_DEBUG("Decompression binary stderr: %s", NULLSTR(errbuf));
4906
    }
4907
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
4908

4909 4910 4911
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
4912
    }
J
Jiri Denemark 已提交
4913

4914
    if (ret < 0) {
4915
        virDomainAuditStart(vm, "restored", false);
J
Jiri Denemark 已提交
4916
        goto out;
4917
    }
4918

4919 4920 4921
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
4922
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
4923 4924 4925
    if (event)
        qemuDomainEventQueue(driver, event);

4926

4927 4928
    /* If it was running before, resume it now unless caller requested pause. */
    if (header->was_running && !start_paused) {
J
Jiri Denemark 已提交
4929
        if (qemuProcessStartCPUs(driver, vm, conn,
4930 4931
                                 VIR_DOMAIN_RUNNING_RESTORED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
4932
            if (virGetLastError() == NULL)
4933 4934
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
4935
            goto out;
4936
        }
4937
        if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0) {
4938
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
4939
            goto out;
4940
        }
4941 4942 4943 4944 4945 4946 4947 4948
    } 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);
4949
    }
J
Jiri Denemark 已提交
4950

4951
    ret = 0;
4952

J
Jiri Denemark 已提交
4953
out:
4954
    virCommandFree(cmd);
4955
    VIR_FREE(errbuf);
4956
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4957
                                                 vm->def, path) < 0)
4958
        VIR_WARN("failed to restore save state label on %s", path);
4959
    virObjectUnref(cfg);
J
Jiri Denemark 已提交
4960 4961 4962
    return ret;
}

4963
static int
4964 4965 4966 4967
qemuDomainRestoreFlags(virConnectPtr conn,
                       const char *path,
                       const char *dxml,
                       unsigned int flags)
4968
{
4969
    virQEMUDriverPtr driver = conn->privateData;
J
Jiri Denemark 已提交
4970 4971 4972 4973
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
4974
    virQEMUSaveHeader header;
J
Jiri Denemark 已提交
4975
    virFileWrapperFdPtr wrapperFd = NULL;
4976
    int state = -1;
J
Jiri Denemark 已提交
4977

4978 4979 4980
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
4981

J
Jiri Denemark 已提交
4982 4983
    qemuDriverLock(driver);

4984 4985 4986 4987 4988
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

4989 4990
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
J
Jiri Denemark 已提交
4991
                                 &wrapperFd, dxml, state, false, false);
J
Jiri Denemark 已提交
4992 4993 4994
    if (fd < 0)
        goto cleanup;

4995 4996
    if (!(vm = virDomainObjListAdd(driver->domains,
                                   driver->caps,
4997 4998 4999 5000
                                   def,
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jiri Denemark 已提交
5001 5002 5003
        goto cleanup;
    def = NULL;

5004
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
5005 5006
        goto cleanup;

5007 5008
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     false);
J
Jiri Denemark 已提交
5009
    if (virFileWrapperFdClose(wrapperFd) < 0)
5010
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
5011

5012
    if (qemuDomainObjEndJob(driver, vm) == 0)
5013
        vm = NULL;
J
Jiri Denemark 已提交
5014
    else if (ret < 0 && !vm->persistent) {
5015
        qemuDomainRemoveInactive(driver, vm);
J
Jiri Denemark 已提交
5016 5017
        vm = NULL;
    }
5018

5019 5020
cleanup:
    virDomainDefFree(def);
5021
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
5022
    virFileWrapperFdFree(wrapperFd);
5023
    if (vm)
5024
        virObjectUnlock(vm);
5025
    qemuDriverUnlock(driver);
5026
    return ret;
D
Daniel P. Berrange 已提交
5027 5028
}

5029 5030 5031 5032 5033 5034 5035
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
    return qemuDomainRestoreFlags(conn, path, NULL, 0);
}

5036 5037 5038 5039
static char *
qemuDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *path,
                              unsigned int flags)
{
5040
    virQEMUDriverPtr driver = conn->privateData;
5041 5042 5043
    char *ret = NULL;
    virDomainDefPtr def = NULL;
    int fd = -1;
5044
    virQEMUSaveHeader header;
5045 5046 5047 5048 5049 5050 5051

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

    qemuDriverLock(driver);

    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
5052
                                 NULL, -1, false, false);
5053 5054 5055 5056

    if (fd < 0)
        goto cleanup;

5057
    ret = qemuDomainDefFormatXML(driver, def, flags);
5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069

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

static int
qemuDomainSaveImageDefineXML(virConnectPtr conn, const char *path,
                             const char *dxml, unsigned int flags)
{
5070
    virQEMUDriverPtr driver = conn->privateData;
5071 5072 5073
    int ret = -1;
    virDomainDefPtr def = NULL;
    int fd = -1;
5074
    virQEMUSaveHeader header;
5075 5076
    char *xml = NULL;
    size_t len;
5077
    int state = -1;
5078

5079 5080
    virCheckFlags(VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
5081 5082 5083

    qemuDriverLock(driver);

5084 5085 5086 5087 5088
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

5089
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
5090
                                 dxml, state, true, false);
5091 5092 5093 5094 5095 5096 5097 5098

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

5099 5100
    xml = qemuDomainDefFormatXML(driver, def,
                                 VIR_DOMAIN_XML_INACTIVE |
5101 5102
                                 VIR_DOMAIN_XML_SECURE |
                                 VIR_DOMAIN_XML_MIGRATABLE);
5103 5104 5105 5106 5107
    if (!xml)
        goto cleanup;
    len = strlen(xml) + 1;

    if (len > header.xml_len) {
5108 5109
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("new xml too large to fit in file"));
5110 5111 5112 5113 5114 5115 5116
        goto cleanup;
    }
    if (VIR_EXPAND_N(xml, len, header.xml_len - len) < 0) {
        virReportOOMError();
        goto cleanup;
    }

5117
    if (lseek(fd, 0, SEEK_SET) != 0) {
5118 5119 5120
        virReportSystemError(errno, _("cannot seek in '%s'"), path);
        goto cleanup;
    }
5121 5122
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header) ||
        safewrite(fd, xml, len) != len ||
5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137
        VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("failed to write xml to '%s'"), path);
        goto cleanup;
    }

    ret = 0;

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

E
Eric Blake 已提交
5138 5139
/* Return 0 on success, 1 if incomplete saved image was silently unlinked,
 * and -1 on failure with error raised.  */
5140 5141
static int
qemuDomainObjRestore(virConnectPtr conn,
5142
                     virQEMUDriverPtr driver,
5143
                     virDomainObjPtr vm,
5144
                     const char *path,
5145
                     bool start_paused,
5146
                     bool bypass_cache)
J
Jiri Denemark 已提交
5147 5148 5149 5150
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
5151
    virQEMUSaveHeader header;
J
Jiri Denemark 已提交
5152
    virFileWrapperFdPtr wrapperFd = NULL;
J
Jiri Denemark 已提交
5153

5154
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
J
Jiri Denemark 已提交
5155
                                 bypass_cache, &wrapperFd, NULL, -1, false,
5156
                                 true);
E
Eric Blake 已提交
5157 5158 5159
    if (fd < 0) {
        if (fd == -3)
            ret = 1;
J
Jiri Denemark 已提交
5160
        goto cleanup;
E
Eric Blake 已提交
5161
    }
J
Jiri Denemark 已提交
5162 5163 5164 5165 5166 5167 5168

    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);
5169 5170 5171 5172 5173
        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 已提交
5174 5175 5176
        goto cleanup;
    }

5177
    virDomainObjAssignDef(vm, def, true, NULL);
J
Jiri Denemark 已提交
5178 5179
    def = NULL;

5180 5181
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     start_paused);
J
Jiri Denemark 已提交
5182
    if (virFileWrapperFdClose(wrapperFd) < 0)
5183
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
5184 5185 5186

cleanup:
    virDomainDefFree(def);
5187
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
5188
    virFileWrapperFdFree(wrapperFd);
J
Jiri Denemark 已提交
5189 5190 5191
    return ret;
}

D
Daniel P. Berrange 已提交
5192

5193
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
5194 5195
                                  unsigned int flags)
{
5196
    virQEMUDriverPtr driver = dom->conn->privateData;
5197 5198
    virDomainObjPtr vm;
    char *ret = NULL;
5199
    unsigned long long balloon;
5200
    int err = 0;
5201
    qemuDomainObjPrivatePtr priv;
5202

5203
    /* Flags checked by virDomainDefFormat */
5204

5205
    qemuDriverLock(driver);
5206
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
5207

D
Daniel P. Berrange 已提交
5208
    if (!vm) {
5209 5210
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5211 5212
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
5213
        goto cleanup;
D
Daniel P. Berrange 已提交
5214 5215
    }

5216 5217
    priv = vm->privateData;

5218 5219 5220
    /* Refresh current memory based on balloon info if supported */
    if ((vm->def->memballoon != NULL) &&
        (vm->def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_NONE) &&
5221
        !qemuCapsGet(priv->caps, QEMU_CAPS_BALLOON_EVENT) &&
5222
        (virDomainObjIsActive(vm))) {
5223 5224
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
5225
        if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
5226
            if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_QUERY) < 0)
5227 5228
                goto cleanup;

5229
            if (!virDomainObjIsActive(vm)) {
5230 5231
                virReportError(VIR_ERR_OPERATION_INVALID,
                               "%s", _("domain is not running"));
5232 5233 5234
                goto endjob;
            }

5235
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
5236
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
5237
            qemuDomainObjExitMonitorWithDriver(driver, vm);
5238 5239

endjob:
5240
            if (qemuDomainObjEndJob(driver, vm) == 0) {
5241 5242 5243
                vm = NULL;
                goto cleanup;
            }
5244 5245 5246
            if (err < 0)
                goto cleanup;
            if (err > 0)
5247
                vm->def->mem.cur_balloon = balloon;
5248 5249
            /* err == 0 indicates no balloon support, so ignore it */
        }
5250
    }
5251

5252 5253 5254 5255
    if ((flags & VIR_DOMAIN_XML_MIGRATABLE))
        flags |= QEMU_DOMAIN_FORMAT_LIVE_FLAGS;

    ret = qemuDomainFormatXML(driver, vm, flags);
5256 5257

cleanup:
5258
    if (vm)
5259
        virObjectUnlock(vm);
5260
    qemuDriverUnlock(driver);
5261
    return ret;
D
Daniel P. Berrange 已提交
5262 5263 5264
}


5265 5266 5267
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
E
Eric Blake 已提交
5268 5269
                                     unsigned int flags)
{
5270
    virQEMUDriverPtr driver = conn->privateData;
5271 5272 5273
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
5274 5275
    virCheckFlags(0, NULL);

5276
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
5277 5278
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), format);
5279 5280 5281
        goto cleanup;
    }

5282
    qemuDriverLock(driver);
5283 5284
    def = qemuParseCommandLineString(driver->caps, config,
                                     NULL, NULL, NULL);
5285
    qemuDriverUnlock(driver);
5286 5287 5288
    if (!def)
        goto cleanup;

5289 5290 5291 5292 5293 5294
    if (!def->name &&
        !(def->name = strdup("unnamed"))) {
        virReportOOMError();
        goto cleanup;
    }

5295
    xml = qemuDomainDefFormatXML(driver, def, VIR_DOMAIN_XML_INACTIVE);
5296 5297 5298 5299 5300 5301

cleanup:
    virDomainDefFree(def);
    return xml;
}

5302 5303 5304
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
E
Eric Blake 已提交
5305 5306
                                   unsigned int flags)
{
5307
    virQEMUDriverPtr driver = conn->privateData;
5308
    virDomainDefPtr def = NULL;
5309
    virDomainChrSourceDef monConfig;
5310
    qemuCapsPtr caps = NULL;
T
tangchen 已提交
5311
    bool monitor_json = false;
E
Eric Blake 已提交
5312
    virCommandPtr cmd = NULL;
5313 5314
    char *ret = NULL;
    int i;
5315
    virQEMUDriverConfigPtr cfg;
5316

E
Eric Blake 已提交
5317 5318
    virCheckFlags(0, NULL);

5319
    qemuDriverLock(driver);
5320
    cfg = virQEMUDriverGetConfig(driver);
5321

5322
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
5323 5324
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), format);
5325 5326 5327
        goto cleanup;
    }

M
Matthias Bolte 已提交
5328 5329
    def = virDomainDefParseString(driver->caps, xmlData,
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
5330 5331 5332
    if (!def)
        goto cleanup;

5333 5334 5335
    if (!(caps = qemuCapsCacheLookup(driver->capsCache, def->emulator)))
        goto cleanup;

5336 5337
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
5338 5339 5340 5341 5342
     * directly. We convert those configs into generic 'ethernet'
     * config and assume the user has suitable 'ifup-qemu' scripts
     */
    for (i = 0 ; i < def->nnets ; i++) {
        virDomainNetDefPtr net = def->nets[i];
5343
        int bootIndex = net->info.bootIndex;
5344 5345
        char *model = net->model;

5346 5347 5348 5349
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            int actualType = virDomainNetGetActualType(net);
            const char *brname;

5350
            VIR_FREE(net->data.network.name);
5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362
            VIR_FREE(net->data.network.portgroup);
            if ((actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
                (brname = virDomainNetGetActualBridgeName(net))) {

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

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

5363
                memset(net, 0, sizeof(*net));
5364 5365

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5366
                net->script = NULL;
5367 5368 5369 5370 5371 5372 5373
                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);
5374
                memset(net, 0, sizeof(*net));
5375 5376

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5377
                net->script = NULL;
5378 5379 5380 5381 5382
                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);
5383

5384
            memset(net, 0, sizeof(*net));
5385 5386

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5387
            net->script = NULL;
5388 5389 5390
            net->data.ethernet.dev = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
5391
            char *script = net->script;
5392 5393 5394
            char *brname = net->data.bridge.brname;
            char *ipaddr = net->data.bridge.ipaddr;

5395
            memset(net, 0, sizeof(*net));
5396 5397

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5398
            net->script = script;
5399 5400 5401
            net->data.ethernet.dev = brname;
            net->data.ethernet.ipaddr = ipaddr;
        }
5402

5403
        VIR_FREE(net->virtPortProfile);
5404
        net->info.bootIndex = bootIndex;
5405
        net->model = model;
5406 5407
    }

5408
    monitor_json = qemuCapsGet(caps, QEMU_CAPS_MONITOR_JSON);
T
tangchen 已提交
5409

5410
    if (qemuProcessPrepareMonitorChr(cfg, &monConfig, def->name) < 0)
5411
        goto cleanup;
5412

5413
    if (qemuAssignDeviceAliases(def, caps) < 0)
5414 5415
        goto cleanup;

5416
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
5417
                                     &monConfig, monitor_json, caps,
5418
                                     NULL, -1, NULL, VIR_NETDEV_VPORT_PROFILE_OP_NO_OP)))
5419 5420
        goto cleanup;

E
Eric Blake 已提交
5421
    ret = virCommandToString(cmd);
5422 5423

cleanup:
5424
    qemuDriverUnlock(driver);
5425

5426
    virObjectUnref(caps);
E
Eric Blake 已提交
5427
    virCommandFree(cmd);
5428
    virDomainDefFree(def);
5429
    virObjectUnref(cfg);
5430 5431 5432 5433
    return ret;
}


5434 5435
static int qemuListDefinedDomains(virConnectPtr conn,
                                  char **const names, int nnames) {
5436
    virQEMUDriverPtr driver = conn->privateData;
5437
    int n;
5438

5439
    qemuDriverLock(driver);
5440
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames);
5441
    qemuDriverUnlock(driver);
5442
    return n;
D
Daniel P. Berrange 已提交
5443 5444
}

5445
static int qemuNumDefinedDomains(virConnectPtr conn) {
5446
    virQEMUDriverPtr driver = conn->privateData;
5447
    int n;
5448

5449
    qemuDriverLock(driver);
5450
    n = virDomainObjListNumOfDomains(driver->domains, 0);
5451
    qemuDriverUnlock(driver);
5452

5453
    return n;
D
Daniel P. Berrange 已提交
5454 5455 5456
}


5457 5458
static int
qemuDomainObjStart(virConnectPtr conn,
5459
                   virQEMUDriverPtr driver,
5460
                   virDomainObjPtr vm,
5461
                   unsigned int flags)
J
Jiri Denemark 已提交
5462 5463 5464
{
    int ret = -1;
    char *managed_save;
5465 5466 5467 5468
    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;
5469 5470 5471 5472
    unsigned int start_flags = VIR_QEMU_PROCESS_START_COLD;

    start_flags |= start_paused ? VIR_QEMU_PROCESS_START_PAUSED : 0;
    start_flags |= autodestroy ? VIR_QEMU_PROCESS_START_AUTODESROY : 0;
J
Jiri Denemark 已提交
5473 5474 5475

    /*
     * If there is a managed saved state restore it instead of starting
5476
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
5477 5478
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
5479 5480 5481 5482

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
5483
    if (virFileExists(managed_save)) {
5484 5485 5486 5487 5488 5489 5490 5491 5492
        if (force_boot) {
            if (unlink(managed_save) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove managed save file %s"),
                                     managed_save);
                goto cleanup;
            }
        } else {
            ret = qemuDomainObjRestore(conn, driver, vm, managed_save,
5493
                                       start_paused, bypass_cache);
J
Jiri Denemark 已提交
5494

5495 5496 5497 5498 5499 5500 5501
            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 已提交
5502 5503 5504 5505
            if (ret > 0)
                VIR_WARN("Ignoring incomplete managed state %s", managed_save);
            else
                goto cleanup;
5506
        }
J
Jiri Denemark 已提交
5507 5508
    }

5509 5510
    ret = qemuProcessStart(conn, driver, vm, NULL, -1, NULL, NULL,
                           VIR_NETDEV_VPORT_PROFILE_OP_CREATE, start_flags);
5511
    virDomainAuditStart(vm, "booted", ret >= 0);
5512
    if (ret >= 0) {
J
Jiri Denemark 已提交
5513 5514 5515 5516
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
5517
        if (event) {
J
Jiri Denemark 已提交
5518
            qemuDomainEventQueue(driver, event);
5519 5520 5521 5522 5523 5524 5525 5526
            if (start_paused) {
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_SUSPENDED,
                                                 VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
                if (event)
                    qemuDomainEventQueue(driver, event);
            }
        }
J
Jiri Denemark 已提交
5527 5528 5529 5530 5531 5532 5533
    }

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

5534
static int
5535
qemuDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
5536
{
5537
    virQEMUDriverPtr driver = dom->conn->privateData;
5538 5539
    virDomainObjPtr vm;
    int ret = -1;
5540

5541
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
5542
                  VIR_DOMAIN_START_AUTODESTROY |
5543 5544
                  VIR_DOMAIN_START_BYPASS_CACHE |
                  VIR_DOMAIN_START_FORCE_BOOT, -1);
5545

5546
    qemuDriverLock(driver);
5547
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
5548

5549
    if (!vm) {
5550 5551
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5552 5553
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
5554
        goto cleanup;
5555 5556
    }

5557
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
5558 5559 5560
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
5561 5562
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is already running"));
5563 5564 5565
        goto endjob;
    }

5566
    if (qemuDomainObjStart(dom->conn, driver, vm, flags) < 0)
5567 5568 5569
        goto endjob;

    ret = 0;
5570

5571
endjob:
5572
    if (qemuDomainObjEndJob(driver, vm) == 0)
5573
        vm = NULL;
5574

5575
cleanup:
5576
    if (vm)
5577
        virObjectUnlock(vm);
5578
    qemuDriverUnlock(driver);
5579
    return ret;
D
Daniel P. Berrange 已提交
5580 5581
}

5582
static int
5583
qemuDomainStart(virDomainPtr dom)
5584
{
5585
    return qemuDomainStartWithFlags(dom, 0);
5586 5587
}

5588
static virDomainPtr qemuDomainDefine(virConnectPtr conn, const char *xml) {
5589
    virQEMUDriverPtr driver = conn->privateData;
5590
    virDomainDefPtr def;
5591
    virDomainDefPtr oldDef = NULL;
5592
    virDomainObjPtr vm = NULL;
5593
    virDomainPtr dom = NULL;
5594
    virDomainEventPtr event = NULL;
5595
    qemuCapsPtr caps = NULL;
5596
    virQEMUDriverConfigPtr cfg;
5597

5598
    qemuDriverLock(driver);
5599
    cfg = virQEMUDriverGetConfig(driver);
5600
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
5601
                                        QEMU_EXPECTED_VIRT_TYPES,
5602
                                        VIR_DOMAIN_XML_INACTIVE)))
5603
        goto cleanup;
5604

5605
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
5606 5607
        goto cleanup;

5608 5609 5610
    if (!(caps = qemuCapsCacheLookup(driver->capsCache, def->emulator)))
        goto cleanup;

5611
    if (qemuCanonicalizeMachine(def, caps) < 0)
5612 5613
        goto cleanup;

5614
    if (qemuDomainAssignAddresses(def, caps, NULL) < 0)
5615 5616
        goto cleanup;

5617 5618 5619 5620 5621 5622 5623
    if (!(vm = virDomainObjListAdd(driver->domains,
                                   driver->caps,
                                   def,
                                   0,
                                   &oldDef)))
        goto cleanup;

5624
    def = NULL;
E
Eric Blake 已提交
5625 5626 5627
    if (virDomainHasDiskMirror(vm)) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE, "%s",
                       _("domain has active block copy job"));
5628
        virDomainObjAssignDef(vm, NULL, false, NULL);
E
Eric Blake 已提交
5629 5630
        goto cleanup;
    }
5631
    vm->persistent = 1;
5632

5633
    if (virDomainSaveConfig(cfg->configDir,
5634
                            vm->newDef ? vm->newDef : vm->def) < 0) {
5635
        if (oldDef) {
M
Michal Privoznik 已提交
5636 5637 5638 5639
            /* 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))
5640
                vm->newDef = oldDef;
M
Michal Privoznik 已提交
5641
            else
5642 5643
                vm->def = oldDef;
            oldDef = NULL;
M
Michal Privoznik 已提交
5644 5645 5646 5647 5648 5649
        } else {
            /* Brand new domain. Remove it */
            VIR_INFO("Deleting domain '%s'", vm->def->name);
            qemuDomainRemoveInactive(driver, vm);
            vm = NULL;
        }
5650
        goto cleanup;
5651 5652
    }

5653 5654
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
5655
                                     !oldDef ?
5656 5657
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
5658

5659
    VIR_INFO("Creating domain '%s'", vm->def->name);
5660
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
5661
    if (dom) dom->id = vm->def->id;
5662 5663

cleanup:
5664
    virDomainDefFree(oldDef);
5665
    virDomainDefFree(def);
5666
    if (vm)
5667
        virObjectUnlock(vm);
5668 5669
    if (event)
        qemuDomainEventQueue(driver, event);
5670
    virObjectUnref(caps);
5671
    qemuDriverUnlock(driver);
5672
    virObjectUnref(cfg);
5673
    return dom;
D
Daniel P. Berrange 已提交
5674 5675
}

5676 5677
static int
qemuDomainUndefineFlags(virDomainPtr dom,
5678
                        unsigned int flags)
5679
{
5680
    virQEMUDriverPtr driver = dom->conn->privateData;
5681
    virDomainObjPtr vm;
5682
    virDomainEventPtr event = NULL;
5683
    char *name = NULL;
5684
    int ret = -1;
5685
    int nsnapshots;
5686
    virQEMUDriverConfigPtr cfg = NULL;
D
Daniel P. Berrange 已提交
5687

5688 5689
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE |
                  VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
5690

5691
    qemuDriverLock(driver);
5692
    cfg = virQEMUDriverGetConfig(driver);
5693
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
5694

D
Daniel P. Berrange 已提交
5695
    if (!vm) {
5696 5697
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5698 5699
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
5700
        goto cleanup;
D
Daniel P. Berrange 已提交
5701 5702
    }

5703
    if (!vm->persistent) {
5704 5705
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
5706 5707 5708
        goto cleanup;
    }

5709
    if (!virDomainObjIsActive(vm) &&
5710
        (nsnapshots = virDomainSnapshotObjListNum(vm->snapshots, NULL, 0))) {
5711
        if (!(flags & VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)) {
5712 5713 5714 5715
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("cannot delete inactive domain with %d "
                             "snapshots"),
                           nsnapshots);
5716 5717
            goto cleanup;
        }
5718
        if (qemuDomainSnapshotDiscardAllMetadata(driver, vm) < 0)
5719
            goto cleanup;
5720 5721
    }

5722 5723 5724 5725 5726 5727 5728
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
5729 5730 5731
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed "
                                 "save image"));
5732 5733 5734
                goto cleanup;
            }
        } else {
5735 5736 5737
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
5738 5739 5740 5741
            goto cleanup;
        }
    }

5742
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
5743
        goto cleanup;
D
Daniel P. Berrange 已提交
5744

5745 5746 5747
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
5748

5749
    VIR_INFO("Undefining domain '%s'", vm->def->name);
5750 5751 5752 5753 5754 5755 5756 5757

    /* 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 {
5758
        qemuDomainRemoveInactive(driver, vm);
5759 5760 5761
        vm = NULL;
    }

5762
    ret = 0;
D
Daniel P. Berrange 已提交
5763

5764
cleanup:
5765
    VIR_FREE(name);
5766
    if (vm)
5767
        virObjectUnlock(vm);
5768 5769
    if (event)
        qemuDomainEventQueue(driver, event);
5770
    qemuDriverUnlock(driver);
5771
    virObjectUnref(cfg);
5772
    return ret;
D
Daniel P. Berrange 已提交
5773 5774
}

5775
static int
5776
qemuDomainUndefine(virDomainPtr dom)
5777 5778 5779 5780
{
    return qemuDomainUndefineFlags(dom, 0);
}

5781
static int
5782
qemuDomainAttachDeviceDiskLive(virConnectPtr conn,
5783
                               virQEMUDriverPtr driver,
5784
                               virDomainObjPtr vm,
5785
                               virDomainDeviceDefPtr dev)
5786 5787 5788 5789
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
5790

5791
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
5792 5793 5794
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unsupported driver name '%s' for disk '%s'"),
                       disk->driverName, disk->src);
5795 5796 5797
        goto end;
    }

5798 5799 5800 5801 5802
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
        disk->shared &&
        (qemuCheckSharedDisk(driver->sharedDisks, disk) < 0))
        goto end;

5803 5804 5805
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto end;

5806 5807
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0)) {
5808 5809 5810
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
5811 5812
            goto end;
        }
5813
        if (qemuSetupDiskCgroup(vm, cgroup, disk) < 0)
5814 5815 5816 5817 5818
            goto end;
    }
    switch (disk->device)  {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
5819
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
5820 5821
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
5822
    case VIR_DOMAIN_DISK_DEVICE_LUN:
5823 5824
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
5825 5826
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("disk device='lun' is not supported for usb bus"));
5827 5828
                break;
            }
5829
            ret = qemuDomainAttachUsbMassstorageDevice(conn, driver, vm,
5830
                                                       disk);
5831
        } else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
5832
            ret = qemuDomainAttachPciDiskDevice(conn, driver, vm, disk);
5833
        } else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
5834
            ret = qemuDomainAttachSCSIDisk(conn, driver, vm, disk);
5835
        } else {
5836 5837 5838
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(disk->bus));
5839
        }
5840 5841
        break;
    default:
5842 5843 5844
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk device type '%s' cannot be hotplugged"),
                       virDomainDiskDeviceTypeToString(disk->device));
5845 5846 5847 5848
        break;
    }

    if (ret != 0 && cgroup) {
5849
        if (qemuTeardownDiskCgroup(vm, cgroup, disk) < 0)
5850 5851 5852
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(disk->src));
    }
5853

5854 5855 5856 5857 5858 5859 5860 5861 5862
    if (ret == 0) {
        if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK && disk->shared) {
            if (qemuAddSharedDisk(driver->sharedDisks, disk->src) < 0)
                VIR_WARN("Failed to add disk '%s' to shared disk table",
                         disk->src);
        }

        if (qemuSetUnprivSGIO(disk) < 0)
            VIR_WARN("Failed to set unpriv_sgio of disk '%s'", disk->src);
5863 5864
    }

5865 5866 5867 5868 5869 5870 5871
end:
    if (cgroup)
        virCgroupFree(&cgroup);
    return ret;
}

static int
5872
qemuDomainAttachDeviceControllerLive(virQEMUDriverPtr driver,
5873
                                     virDomainObjPtr vm,
5874
                                     virDomainDeviceDefPtr dev)
5875 5876 5877 5878 5879 5880
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5881
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
5882 5883
        break;
    default:
5884 5885 5886
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk controller bus '%s' cannot be hotplugged."),
                       virDomainControllerTypeToString(cont->type));
5887 5888 5889 5890 5891 5892 5893 5894
        break;
    }
    return ret;
}

static int
qemuDomainAttachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
5895
                           virDomainPtr dom)
5896
{
5897
    virQEMUDriverPtr driver = dom->conn->privateData;
5898 5899 5900 5901
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5902
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
5903
        ret = qemuDomainAttachDeviceDiskLive(dom->conn, driver, vm, dev);
5904 5905 5906 5907 5908
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
5909
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
5910 5911 5912 5913
        if (!ret)
            dev->data.controller = NULL;
        break;

5914 5915 5916 5917 5918 5919 5920
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

5921
    case VIR_DOMAIN_DEVICE_NET:
5922
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
5923
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
5924
                                        dev->data.net);
5925 5926 5927 5928 5929 5930
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
5931
                                         dev->data.hostdev);
5932 5933 5934 5935
        if (!ret)
            dev->data.hostdev = NULL;
        break;

5936 5937 5938 5939 5940 5941 5942
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        ret = qemuDomainAttachRedirdevDevice(driver, vm,
                                             dev->data.redirdev);
        if (!ret)
            dev->data.redirdev = NULL;
        break;

5943
    default:
5944 5945 5946
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be attached"),
                       virDomainDeviceTypeToString(dev->type));
5947 5948 5949 5950 5951 5952 5953
        break;
    }

    return ret;
}

static int
5954
qemuDomainDetachDeviceDiskLive(virQEMUDriverPtr driver,
5955
                               virDomainObjPtr vm,
5956
                               virDomainDeviceDefPtr dev)
5957 5958 5959 5960 5961 5962
{
    virDomainDiskDefPtr disk = dev->data.disk;
    int ret = -1;

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_DISK:
5963
    case VIR_DOMAIN_DISK_DEVICE_LUN:
5964
        if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
5965
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
O
Osier Yang 已提交
5966 5967
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                 disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5968
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
5969
        else
5970 5971
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("This type of disk cannot be hot unplugged"));
5972 5973
        break;
    default:
5974 5975 5976
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk device type '%s' cannot be detached"),
                       virDomainDiskDeviceTypeToString(disk->type));
5977 5978
        break;
    }
5979 5980 5981 5982 5983 5984 5985 5986 5987

    if (ret == 0 &&
        disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
        disk->shared) {
        if (qemuRemoveSharedDisk(driver->sharedDisks, disk->src) < 0)
             VIR_WARN("Failed to remove disk '%s' from shared disk table",
                      disk->src);
    }

5988 5989 5990 5991
    return ret;
}

static int
5992
qemuDomainDetachDeviceControllerLive(virQEMUDriverPtr driver,
5993
                                     virDomainObjPtr vm,
5994
                                     virDomainDeviceDefPtr dev)
5995 5996 5997 5998 5999 6000
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
6001
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
6002 6003
        break;
    default :
6004 6005 6006
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk controller bus '%s' cannot be hotunplugged."),
                       virDomainControllerTypeToString(cont->type));
6007 6008 6009 6010 6011 6012 6013
    }
    return ret;
}

static int
qemuDomainDetachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
6014
                           virDomainPtr dom)
6015
{
6016
    virQEMUDriverPtr driver = dom->conn->privateData;
6017 6018 6019 6020
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
6021
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
6022 6023
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
6024
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
6025
        break;
6026 6027 6028
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
6029
    case VIR_DOMAIN_DEVICE_NET:
6030
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
6031 6032
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
6033
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
6034 6035
        break;
    default:
6036 6037
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("This type of device cannot be hot unplugged"));
6038 6039 6040 6041 6042 6043
        break;
    }

    return ret;
}

6044 6045 6046
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
6047
                              virQEMUDriverPtr driver,
6048 6049 6050 6051
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
6052
    int ret = -1;
6053

6054 6055 6056
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto end;

6057 6058
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
6059
                               vm->def->name, &cgroup, 0) != 0) {
6060 6061 6062
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
6063 6064
            goto end;
        }
6065
        if (qemuSetupDiskCgroup(vm, cgroup, disk) < 0)
6066 6067 6068 6069 6070 6071
            goto end;
    }

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
6072
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
6073 6074 6075 6076
        if (ret == 0)
            dev->data.disk = NULL;
        break;
    default:
6077 6078 6079
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk bus '%s' cannot be updated."),
                       virDomainDiskBusTypeToString(disk->bus));
6080 6081 6082 6083
        break;
    }

    if (ret != 0 && cgroup) {
6084
        if (qemuTeardownDiskCgroup(vm, cgroup, disk) < 0)
6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099
             VIR_WARN("Failed to teardown cgroup for disk path %s",
                      NULLSTR(disk->src));
    }
end:
    if (cgroup)
        virCgroupFree(&cgroup);
    return ret;
}

static int
qemuDomainUpdateDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
                           virDomainPtr dom,
                           bool force)
{
6100
    virQEMUDriverPtr driver = dom->conn->privateData;
6101 6102 6103 6104
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
6105
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
6106 6107 6108 6109
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
6110
    case VIR_DOMAIN_DEVICE_NET:
6111
        ret = qemuDomainChangeNet(driver, vm, dom, dev);
6112
        break;
6113
    default:
6114 6115 6116
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be updated"),
                       virDomainDeviceTypeToString(dev->type));
6117 6118 6119 6120 6121 6122
        break;
    }

    return ret;
}

6123
static int
6124 6125
qemuDomainAttachDeviceConfig(qemuCapsPtr caps,
                             virDomainDefPtr vmdef,
6126 6127
                             virDomainDeviceDefPtr dev)
{
6128
    virDomainDiskDefPtr disk;
6129
    virDomainNetDefPtr net;
6130
    virDomainHostdevDefPtr hostdev;
6131
    virDomainLeaseDefPtr lease;
6132
    virDomainControllerDefPtr controller;
6133

6134
    switch (dev->type) {
6135 6136
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
6137
        if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
6138 6139
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("target %s already exists"), disk->dst);
6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150
            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;
6151
        if (qemuDomainAssignAddresses(vmdef, caps, NULL) < 0)
6152 6153 6154
            return -1;
        break;

6155 6156 6157 6158 6159 6160 6161
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetInsert(vmdef, net)) {
            virReportOOMError();
            return -1;
        }
        dev->data.net = NULL;
6162
        if (qemuDomainAssignAddresses(vmdef, caps, NULL) < 0)
6163 6164
            return -1;
        break;
6165

6166 6167 6168
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        hostdev = dev->data.hostdev;
        if (virDomainHostdevFind(vmdef, hostdev, NULL) >= 0) {
6169
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
6170
                           _("device is already in the domain configuration"));
6171 6172 6173 6174 6175 6176 6177
            return -1;
        }
        if (virDomainHostdevInsert(vmdef, hostdev)) {
            virReportOOMError();
            return -1;
        }
        dev->data.hostdev = NULL;
6178
        if (qemuDomainAssignAddresses(vmdef, caps, NULL) < 0)
6179 6180 6181
            return -1;
        break;

6182 6183 6184
    case VIR_DOMAIN_DEVICE_LEASE:
        lease = dev->data.lease;
        if (virDomainLeaseIndex(vmdef, lease) >= 0) {
6185
            virReportError(VIR_ERR_OPERATION_INVALID,
6186 6187
                           _("Lease %s in lockspace %s already exists"),
                           lease->key, NULLSTR(lease->lockspace));
6188 6189 6190 6191 6192 6193 6194 6195 6196
            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;

6197 6198 6199 6200
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        controller = dev->data.controller;
        if (virDomainControllerFind(vmdef, controller->type,
                                    controller->idx) > 0) {
6201
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
6202 6203 6204 6205 6206 6207 6208 6209
                           _("Target already exists"));
            return -1;
        }

        if (virDomainControllerInsert(vmdef, controller) < 0)
            return -1;
        dev->data.controller = NULL;

6210
        if (qemuDomainAssignAddresses(vmdef, caps, NULL) < 0)
6211 6212 6213
            return -1;
        break;

6214
    default:
6215 6216
         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent attach of device is not supported"));
6217 6218 6219 6220 6221 6222 6223
         return -1;
    }
    return 0;
}


static int
6224
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
6225 6226
                             virDomainDeviceDefPtr dev)
{
6227
    virDomainDiskDefPtr disk, det_disk;
6228
    virDomainNetDefPtr net;
6229
    virDomainHostdevDefPtr hostdev, det_hostdev;
6230
    virDomainLeaseDefPtr lease, det_lease;
6231 6232
    virDomainControllerDefPtr cont, det_cont;
    int idx;
6233
    char mac[VIR_MAC_STRING_BUFLEN];
6234

6235
    switch (dev->type) {
6236 6237
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
6238
        if (!(det_disk = virDomainDiskRemoveByName(vmdef, disk->dst))) {
6239 6240
            virReportError(VIR_ERR_INVALID_ARG,
                           _("no target device %s"), disk->dst);
6241 6242
            return -1;
        }
6243
        virDomainDiskDefFree(det_disk);
6244
        break;
6245

6246 6247
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
6248 6249 6250 6251 6252 6253 6254 6255 6256
        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"));
6257 6258
            return -1;
        }
6259 6260
        /* this is guaranteed to succeed */
        virDomainNetDefFree(virDomainNetRemove(vmdef, idx));
6261
        break;
6262

6263 6264 6265
    case VIR_DOMAIN_DEVICE_HOSTDEV: {
        hostdev = dev->data.hostdev;
        if ((idx = virDomainHostdevFind(vmdef, hostdev, &det_hostdev)) < 0) {
6266 6267
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("device not present in domain configuration"));
6268 6269 6270 6271 6272 6273 6274
            return -1;
        }
        virDomainHostdevRemove(vmdef, idx);
        virDomainHostdevDefFree(det_hostdev);
        break;
    }

6275 6276
    case VIR_DOMAIN_DEVICE_LEASE:
        lease = dev->data.lease;
6277
        if (!(det_lease = virDomainLeaseRemove(vmdef, lease))) {
6278 6279 6280
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Lease %s in lockspace %s does not exist"),
                           lease->key, NULLSTR(lease->lockspace));
6281 6282
            return -1;
        }
6283
        virDomainLeaseDefFree(det_lease);
6284 6285
        break;

6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298
    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;

6299
    default:
6300 6301
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("persistent detach of device is not supported"));
6302 6303 6304 6305 6306 6307
        return -1;
    }
    return 0;
}

static int
6308 6309
qemuDomainUpdateDeviceConfig(qemuCapsPtr caps,
                             virDomainDefPtr vmdef,
6310 6311
                             virDomainDeviceDefPtr dev)
{
6312
    virDomainDiskDefPtr orig, disk;
6313
    virDomainNetDefPtr net;
6314
    int pos;
6315 6316
    char mac[VIR_MAC_STRING_BUFLEN];

6317

6318
    switch (dev->type) {
6319 6320
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
6321
        pos = virDomainDiskIndexByName(vmdef, disk->dst, false);
6322
        if (pos < 0) {
6323 6324
            virReportError(VIR_ERR_INVALID_ARG,
                           _("target %s doesn't exist."), disk->dst);
6325 6326 6327 6328 6329
            return -1;
        }
        orig = vmdef->disks[pos];
        if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
            !(orig->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)) {
6330 6331
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("this disk doesn't support update"));
6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346
            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;
        }
6347 6348
        if (disk->format)
            orig->format = disk->format;
6349 6350
        disk->src = NULL;
        break;
6351 6352 6353

    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365
        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);
6366 6367 6368
            return -1;
        }

6369
        virDomainNetDefFree(vmdef->nets[pos]);
6370 6371 6372 6373

        vmdef->nets[pos] = net;
        dev->data.net = NULL;

6374
        if (qemuDomainAssignAddresses(vmdef, caps, NULL) < 0)
6375 6376 6377
            return -1;
        break;

6378
    default:
6379 6380
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("persistent update of device is not supported"));
6381 6382 6383 6384 6385
        return -1;
    }
    return 0;
}

6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396
/* Actions for qemuDomainModifyDeviceFlags */
enum {
    QEMU_DEVICE_ATTACH,
    QEMU_DEVICE_DETACH,
    QEMU_DEVICE_UPDATE,
};


static int
qemuDomainModifyDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags, int action)
6397
{
6398
    virQEMUDriverPtr driver = dom->conn->privateData;
6399
    virDomainObjPtr vm = NULL;
6400
    virDomainDefPtr vmdef = NULL;
6401
    virDomainDeviceDefPtr dev = NULL, dev_copy = NULL;
6402
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
6403
    int ret = -1;
6404
    unsigned int affect;
6405 6406
    qemuCapsPtr caps = NULL;
    qemuDomainObjPrivatePtr priv;
6407
    virQEMUDriverConfigPtr cfg = NULL;
6408

6409 6410
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
6411 6412 6413
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

6414 6415
    cfg = virQEMUDriverGetConfig(driver);

6416 6417
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

6418
    qemuDriverLock(driver);
6419
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
6420 6421 6422
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6423 6424
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
6425 6426
        goto cleanup;
    }
6427
    priv = vm->privateData;
6428

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

6432
    if (virDomainObjIsActive(vm)) {
6433
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
6434
            flags |= VIR_DOMAIN_AFFECT_LIVE;
6435
    } else {
6436
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
6437
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
6438
        /* check consistency between flags and the vm state */
6439
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6440
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
6441 6442
                           _("cannot do live update a device on "
                             "inactive domain"));
6443 6444
            goto endjob;
        }
6445
    }
6446

6447
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
6448 6449
         virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot modify device on transient domain"));
6450 6451
         goto endjob;
    }
6452

6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465
    dev = dev_copy = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                             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(driver->caps, vm->def, dev);
        if (!dev_copy)
6466
            goto endjob;
6467
    }
6468

6469 6470 6471 6472 6473
    if (priv->caps)
        caps = virObjectRef(priv->caps);
    else if (!(caps = qemuCapsCacheLookup(driver->capsCache, vm->def->emulator)))
        goto cleanup;

6474
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6475
        if (virDomainDefCompatibleDevice(vm->def, dev) < 0)
6476 6477
            goto endjob;

6478 6479 6480 6481 6482 6483
        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto endjob;
        switch (action) {
        case QEMU_DEVICE_ATTACH:
6484
            ret = qemuDomainAttachDeviceConfig(caps, vmdef, dev);
6485 6486 6487 6488 6489
            break;
        case QEMU_DEVICE_DETACH:
            ret = qemuDomainDetachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_UPDATE:
6490
            ret = qemuDomainUpdateDeviceConfig(caps, vmdef, dev);
6491 6492
            break;
        default:
6493 6494
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown domain modify action %d"), action);
6495 6496
            break;
        }
6497

6498 6499 6500 6501 6502
        if (ret == -1)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6503 6504 6505
        if (virDomainDefCompatibleDevice(vm->def, dev_copy) < 0)
            goto endjob;

6506 6507
        switch (action) {
        case QEMU_DEVICE_ATTACH:
6508
            ret = qemuDomainAttachDeviceLive(vm, dev_copy, dom);
6509 6510
            break;
        case QEMU_DEVICE_DETACH:
6511
            ret = qemuDomainDetachDeviceLive(vm, dev_copy, dom);
6512 6513
            break;
        case QEMU_DEVICE_UPDATE:
6514
            ret = qemuDomainUpdateDeviceLive(vm, dev_copy, dom, force);
6515 6516
            break;
        default:
6517 6518
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown domain modify action %d"), action);
6519
            ret = -1;
6520 6521
            break;
        }
6522 6523 6524

        if (ret == -1)
            goto endjob;
6525 6526
        /*
         * update domain status forcibly because the domain status may be
6527 6528
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
6529
         */
6530
        if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0) {
6531
            ret = -1;
6532 6533
            goto endjob;
        }
6534
    }
6535

6536
    /* Finally, if no error until here, we can save config. */
6537
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6538
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
6539
        if (!ret) {
6540
            virDomainObjAssignDef(vm, vmdef, false, NULL);
6541 6542 6543
            vmdef = NULL;
        }
    }
6544 6545

endjob:
6546
    if (qemuDomainObjEndJob(driver, vm) == 0)
6547 6548 6549
        vm = NULL;

cleanup:
6550
    virObjectUnref(caps);
6551
    virDomainDefFree(vmdef);
6552 6553
    if (dev != dev_copy)
        virDomainDeviceDefFree(dev_copy);
6554 6555
    virDomainDeviceDefFree(dev);
    if (vm)
6556
        virObjectUnlock(vm);
6557
    qemuDriverUnlock(driver);
6558
    virObjectUnref(cfg);
6559 6560 6561
    return ret;
}

6562 6563 6564 6565 6566 6567
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

6568 6569 6570
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
6571
                                       VIR_DOMAIN_AFFECT_LIVE);
6572
}
6573

6574

6575 6576 6577 6578
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
6579
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
6580 6581
}

6582 6583 6584
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
6585
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
6586 6587
}

6588 6589 6590
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
6591
                                       VIR_DOMAIN_AFFECT_LIVE);
6592 6593
}

6594 6595
static int qemuDomainGetAutostart(virDomainPtr dom,
                                  int *autostart) {
6596 6597
    virDomainObjPtr vm;
    int ret = -1;
6598

6599
    if (!(vm = qemuDomObjFromDomain(dom)))
6600
        goto cleanup;
6601 6602

    *autostart = vm->autostart;
6603
    ret = 0;
6604

6605
cleanup:
6606
    if (vm)
6607
        virObjectUnlock(vm);
6608
    return ret;
6609 6610
}

6611 6612
static int qemuDomainSetAutostart(virDomainPtr dom,
                                  int autostart) {
6613
    virQEMUDriverPtr driver = dom->conn->privateData;
6614
    virDomainObjPtr vm;
6615 6616
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
6617
    virQEMUDriverConfigPtr cfg = NULL;
6618

6619
    qemuDriverLock(driver);
6620
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
6621
    cfg = virQEMUDriverGetConfig(driver);
6622
    if (!vm) {
6623 6624
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6625 6626
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
6627
        goto cleanup;
6628 6629
    }

6630
    if (!vm->persistent) {
6631 6632
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
6633
        goto cleanup;
6634 6635
    }

6636 6637
    autostart = (autostart != 0);

6638
    if (vm->autostart != autostart) {
6639
        if ((configFile = virDomainConfigFile(cfg->configDir, vm->def->name)) == NULL)
6640
            goto cleanup;
6641
        if ((autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)) == NULL)
6642
            goto cleanup;
6643

6644
        if (autostart) {
6645
            if (virFileMakePath(cfg->autostartDir) < 0) {
6646
                virReportSystemError(errno,
6647
                                     _("cannot create autostart directory %s"),
6648
                                     cfg->autostartDir);
6649 6650
                goto cleanup;
            }
6651

6652
            if (symlink(configFile, autostartLink) < 0) {
6653
                virReportSystemError(errno,
6654 6655
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
6656 6657 6658 6659
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
6660
                virReportSystemError(errno,
6661 6662
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
6663 6664
                goto cleanup;
            }
6665 6666
        }

6667
        vm->autostart = autostart;
6668
    }
6669
    ret = 0;
6670

6671 6672 6673
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
6674
    if (vm)
6675
        virObjectUnlock(vm);
6676
    qemuDriverUnlock(driver);
6677
    virObjectUnref(cfg);
6678
    return ret;
6679 6680
}

6681

6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714
/*
 * 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;
}


6715 6716 6717
static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
6718
    virQEMUDriverPtr driver = dom->conn->privateData;
6719
    char *ret = NULL;
6720
    int rc;
6721

6722
    qemuDriverLock(driver);
6723
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
6724 6725
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cgroup CPU controller is not mounted"));
6726
        goto cleanup;
6727 6728
    }

6729 6730 6731 6732 6733 6734 6735
    if (nparams) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        else if (rc == 0)
            *nparams = 1;
        else
6736
            *nparams = 5;
6737
    }
6738 6739 6740

    ret = strdup("posix");
    if (!ret)
6741
        virReportOOMError();
6742 6743 6744

cleanup:
    qemuDriverUnlock(driver);
6745 6746 6747
    return ret;
}

6748 6749 6750 6751
/* 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
6752 6753
qemuDomainParseDeviceWeightStr(char *deviceWeightStr,
                               virBlkioDeviceWeightPtr *dw, size_t *size)
6754 6755 6756 6757 6758 6759 6760
{
    char *temp;
    int ndevices = 0;
    int nsep = 0;
    int i;
    virBlkioDeviceWeightPtr result = NULL;

6761 6762 6763 6764 6765 6766
    *dw = NULL;
    *size = 0;

    if (STREQ(deviceWeightStr, ""))
        return 0;

6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827
    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;

        result[i].path = strndup(temp, p - temp);
        if (!result[i].path) {
            virReportOOMError();
            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:
6828 6829
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unable to parse device weight '%s'"), deviceWeightStr);
6830 6831 6832 6833 6834 6835
cleanup:
    virBlkioDeviceWeightArrayClear(result, ndevices);
    VIR_FREE(result);
    return -1;
}

6836 6837
/* Modify dest_array to reflect all device weight changes described in
 * src_array.  */
6838
static int
6839 6840 6841 6842
qemuDomainMergeDeviceWeights(virBlkioDeviceWeightPtr *dest_array,
                             size_t *dest_size,
                             virBlkioDeviceWeightPtr src_array,
                             size_t src_size)
6843 6844
{
    int i, j;
6845
    virBlkioDeviceWeightPtr dest, src;
6846

6847
    for (i = 0; i < src_size; i++) {
6848 6849
        bool found = false;

6850 6851 6852 6853
        src = &src_array[i];
        for (j = 0; j < *dest_size; j++) {
            dest = &(*dest_array)[j];
            if (STREQ(src->path, dest->path)) {
6854
                found = true;
6855
                dest->weight = src->weight;
6856 6857 6858 6859
                break;
            }
        }
        if (!found) {
6860
            if (!src->weight)
6861
                continue;
6862
            if (VIR_EXPAND_N(*dest_array, *dest_size, 1) < 0) {
6863 6864 6865
                virReportOOMError();
                return -1;
            }
6866 6867 6868 6869
            dest = &(*dest_array)[*dest_size - 1];
            dest->path = src->path;
            dest->weight = src->weight;
            src->path = NULL;
6870 6871 6872 6873 6874 6875
        }
    }

    return 0;
}

6876 6877 6878 6879 6880
static int
qemuDomainSetBlkioParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int nparams,
                             unsigned int flags)
6881
{
6882
    virQEMUDriverPtr driver = dom->conn->privateData;
6883 6884 6885
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6886
    virDomainDefPtr persistentDef = NULL;
6887
    int ret = -1;
6888
    virQEMUDriverConfigPtr cfg = NULL;
6889

6890 6891
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6892 6893 6894 6895 6896 6897 6898
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_BLKIO_WEIGHT,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                                       VIR_TYPED_PARAM_STRING,
                                       NULL) < 0)
        return -1;
6899

6900
    qemuDriverLock(driver);
6901
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
6902
    if (vm == NULL) {
6903 6904
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
6905 6906
        goto cleanup;
    }
6907
    cfg = virQEMUDriverGetConfig(driver);
6908

6909 6910 6911
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
6912

6913 6914
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
6915 6916
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("blkio cgroup isn't mounted"));
6917 6918 6919 6920
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
6921 6922 6923
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"),
                           vm->def->name);
6924 6925 6926 6927
            goto cleanup;
        }
    }

6928
    ret = 0;
6929 6930
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        for (i = 0; i < nparams; i++) {
6931
            int rc;
6932 6933 6934 6935
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (params[i].value.ui > 1000 || params[i].value.ui < 100) {
6936 6937
                    virReportError(VIR_ERR_INVALID_ARG, "%s",
                                   _("out of blkio weight range."));
6938 6939 6940
                    ret = -1;
                    continue;
                }
6941

6942 6943 6944 6945 6946 6947
                rc = virCgroupSetBlkioWeight(group, params[i].value.ui);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set blkio weight tunable"));
                    ret = -1;
                }
6948
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
6949
                size_t ndevices;
6950
                virBlkioDeviceWeightPtr devices = NULL;
6951 6952
                int j;

6953 6954 6955
                if (qemuDomainParseDeviceWeightStr(params[i].value.s,
                                                   &devices,
                                                   &ndevices) < 0) {
6956 6957 6958
                    ret = -1;
                    continue;
                }
6959
                for (j = 0; j < ndevices; j++) {
6960
                    rc = virCgroupSetBlkioDeviceWeight(group,
6961 6962
                                                       devices[j].path,
                                                       devices[j].weight);
6963 6964 6965 6966
                    if (rc < 0) {
                        virReportSystemError(-rc,
                                             _("Unable to set io device weight "
                                               "for path %s"),
6967
                                             devices[j].path);
6968 6969 6970
                        break;
                    }
                }
6971 6972
                if (j != ndevices ||
                    qemuDomainMergeDeviceWeights(&vm->def->blkio.devices,
6973 6974 6975 6976 6977
                                                 &vm->def->blkio.ndevices,
                                                 devices, ndevices) < 0)
                    ret = -1;
                virBlkioDeviceWeightArrayClear(devices, ndevices);
                VIR_FREE(devices);
6978
            }
6979
        }
E
Eric Blake 已提交
6980 6981 6982 6983
    }
    if (ret < 0)
        goto cleanup;
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
6984 6985 6986
        /* Clang can't see that if we get here, persistentDef was set.  */
        sa_assert(persistentDef);

6987 6988 6989 6990 6991
        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) {
6992 6993
                    virReportError(VIR_ERR_INVALID_ARG, "%s",
                                   _("out of blkio weight range."));
6994 6995 6996 6997 6998
                    ret = -1;
                    continue;
                }

                persistentDef->blkio.weight = params[i].value.ui;
6999 7000
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
                virBlkioDeviceWeightPtr devices = NULL;
7001
                size_t ndevices;
7002

7003 7004 7005
                if (qemuDomainParseDeviceWeightStr(params[i].value.s,
                                                   &devices,
                                                   &ndevices) < 0) {
7006 7007 7008
                    ret = -1;
                    continue;
                }
7009 7010
                if (qemuDomainMergeDeviceWeights(&persistentDef->blkio.devices,
                                                 &persistentDef->blkio.ndevices,
7011 7012 7013 7014
                                                 devices, ndevices) < 0)
                    ret = -1;
                virBlkioDeviceWeightArrayClear(devices, ndevices);
                VIR_FREE(devices);
7015 7016
            }
        }
A
Alex Jia 已提交
7017

7018
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
A
Alex Jia 已提交
7019
            ret = -1;
7020 7021 7022 7023 7024
    }

cleanup:
    virCgroupFree(&group);
    if (vm)
7025
        virObjectUnlock(vm);
7026
    qemuDriverUnlock(driver);
7027
    virObjectUnref(cfg);
7028 7029 7030
    return ret;
}

7031 7032 7033 7034 7035
static int
qemuDomainGetBlkioParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
7036
{
7037
    virQEMUDriverPtr driver = dom->conn->privateData;
7038
    int i, j;
7039 7040
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
7041
    virDomainDefPtr persistentDef = NULL;
7042 7043 7044 7045
    unsigned int val;
    int ret = -1;
    int rc;

7046
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
7047 7048
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
7049 7050
    qemuDriverLock(driver);

7051 7052 7053
    /* 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.  */
7054 7055
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

7056
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
7057 7058

    if (vm == NULL) {
7059 7060
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
7061 7062 7063 7064 7065 7066 7067 7068 7069 7070
        goto cleanup;
    }

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

7071 7072 7073
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
7074

7075 7076
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
7077 7078
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("blkio cgroup isn't mounted"));
7079 7080 7081 7082
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7083 7084
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"), vm->def->name);
7085 7086 7087 7088 7089
            goto cleanup;
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7090
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101
            virTypedParameterPtr param = &params[i];
            val = 0;

            switch (i) {
            case 0: /* fill blkio weight here */
                rc = virCgroupGetBlkioWeight(group, &val);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get blkio weight"));
                    goto cleanup;
                }
7102 7103
                if (virTypedParameterAssign(param, VIR_DOMAIN_BLKIO_WEIGHT,
                                            VIR_TYPED_PARAM_UINT, val) < 0)
7104 7105
                    goto cleanup;
                break;
7106 7107 7108 7109
            case 1: /* blkiotune.device_weight */
                if (vm->def->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
                    bool comma = false;
7110

7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127
                    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);
                }
7128 7129 7130 7131
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                                            VIR_TYPED_PARAM_STRING,
                                            param->value.s) < 0)
7132 7133
                    goto cleanup;
                break;
7134 7135 7136 7137

            default:
                break;
                /* should not hit here */
7138
            }
7139 7140
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7141
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
7142 7143 7144 7145 7146 7147 7148 7149
            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) {
7150 7151 7152
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Field name '%s' too long"),
                                   VIR_DOMAIN_BLKIO_WEIGHT);
7153 7154 7155 7156
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
7157

7158 7159 7160
            case 1: /* blkiotune.device_weight */
                if (persistentDef->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
7161 7162
                    bool comma = false;

7163
                    for (j = 0; j < persistentDef->blkio.ndevices; j++) {
7164 7165 7166
                        if (!persistentDef->blkio.devices[j].weight)
                            continue;
                        if (comma)
7167
                            virBufferAddChar(&buf, ',');
7168 7169
                        else
                            comma = true;
7170 7171 7172 7173 7174 7175 7176 7177 7178
                        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);
7179 7180
                }
                if (!param->value.s) {
7181 7182 7183 7184 7185 7186 7187 7188 7189
                    param->value.s = strdup("");
                    if (!param->value.s) {
                        virReportOOMError();
                        goto cleanup;
                    }
                }
                param->type = VIR_TYPED_PARAM_STRING;
                if (virStrcpyStatic(param->field,
                                    VIR_DOMAIN_BLKIO_DEVICE_WEIGHT) == NULL) {
7190 7191 7192
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Field name '%s' too long"),
                                   VIR_DOMAIN_BLKIO_DEVICE_WEIGHT);
7193 7194 7195 7196
                    goto cleanup;
                }
                break;

7197 7198 7199 7200
            default:
                break;
                /* should not hit here */
            }
7201 7202 7203
        }
    }

7204 7205
    if (QEMU_NB_BLKIO_PARAM < *nparams)
        *nparams = QEMU_NB_BLKIO_PARAM;
7206 7207 7208 7209 7210 7211
    ret = 0;

cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
7212
        virObjectUnlock(vm);
7213 7214 7215
    qemuDriverUnlock(driver);
    return ret;
}
7216

7217 7218 7219 7220 7221
static int
qemuDomainSetMemoryParameters(virDomainPtr dom,
                              virTypedParameterPtr params,
                              int nparams,
                              unsigned int flags)
7222
{
7223
    virQEMUDriverPtr driver = dom->conn->privateData;
7224
    int i;
7225
    virDomainDefPtr persistentDef = NULL;
7226 7227
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
7228 7229 7230 7231 7232
    virTypedParameterPtr hard_limit = NULL;
    virTypedParameterPtr swap_hard_limit = NULL;
    int hard_limit_index = 0;
    int swap_hard_limit_index = 0;
    unsigned long long val = 0;
7233
    virQEMUDriverConfigPtr cfg = NULL;
7234
    int ret = -1;
7235
    int rc;
7236

7237 7238
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
7239

7240 7241 7242 7243 7244 7245 7246 7247 7248
    if (virTypedParameterArrayValidate(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)
        return -1;
7249 7250 7251

    qemuDriverLock(driver);

7252
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
7253 7254

    if (vm == NULL) {
7255 7256
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
7257 7258 7259
        goto cleanup;
    }

7260 7261
    cfg = virQEMUDriverGetConfig(driver);

7262 7263 7264
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
7265

7266
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7267
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
7268 7269
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup memory controller is not mounted"));
7270 7271 7272 7273
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7274 7275
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"), vm->def->name);
7276 7277 7278 7279
            goto cleanup;
        }
    }

7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298
    for (i = 0; i < nparams; i++) {
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
            hard_limit = &params[i];
            hard_limit_index = i;
        } else if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
            swap_hard_limit = &params[i];
            swap_hard_limit_index = i;
        }
    }

    /* It will fail if hard limit greater than swap hard limit anyway */
    if (swap_hard_limit &&
        hard_limit &&
        (hard_limit->value.ul > swap_hard_limit->value.ul)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("hard limit must be lower than swap hard limit"));
        goto cleanup;
    }

7299 7300 7301 7302 7303 7304 7305 7306
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        /* Get current swap hard limit */
        rc = virCgroupGetMemSwapHardLimit(group, &val);
        if (rc != 0) {
            virReportSystemError(-rc, "%s",
                                 _("unable to get swap hard limit"));
            goto cleanup;
        }
7307

7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326
        /* Swap hard_limit and swap_hard_limit to ensure the setting
         * could succeed if both of them are provided.
         */
        if (swap_hard_limit && hard_limit) {
            virTypedParameter param;

            if (swap_hard_limit->value.ul > val) {
                if (hard_limit_index < swap_hard_limit_index) {
                    param = params[hard_limit_index];
                    params[hard_limit_index] = params[swap_hard_limit_index];
                    params[swap_hard_limit_index] = param;
                }
            } else {
                if (hard_limit_index > swap_hard_limit_index) {
                    param = params[hard_limit_index];
                    params[hard_limit_index] = params[swap_hard_limit_index];
                    params[swap_hard_limit_index] = param;
                }
            }
7327 7328 7329
        }
    }

7330 7331
    ret = 0;
    for (i = 0; i < nparams; i++) {
7332
        virTypedParameterPtr param = &params[i];
7333 7334

        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
7335
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7336
                rc = virCgroupSetMemoryHardLimit(group, param->value.ul);
7337 7338 7339 7340 7341 7342 7343
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

7344
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7345
                persistentDef->mem.hard_limit = param->value.ul;
7346 7347
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
7348
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7349
                rc = virCgroupSetMemorySoftLimit(group, param->value.ul);
7350 7351 7352 7353 7354 7355 7356
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

7357
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7358
                persistentDef->mem.soft_limit = param->value.ul;
7359
            }
7360
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
7361
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7362
                rc = virCgroupSetMemSwapHardLimit(group, param->value.ul);
7363 7364 7365 7366 7367 7368
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
7369
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7370
                persistentDef->mem.swap_hard_limit = param->value.ul;
7371 7372 7373 7374
            }
        }
    }

7375
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7376
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
7377
            ret = -1;
7378 7379
    }

7380 7381 7382
cleanup:
    virCgroupFree(&group);
    if (vm)
7383
        virObjectUnlock(vm);
7384
    qemuDriverUnlock(driver);
7385
    virObjectUnref(cfg);
7386 7387 7388
    return ret;
}

7389 7390 7391 7392 7393
static int
qemuDomainGetMemoryParameters(virDomainPtr dom,
                              virTypedParameterPtr params,
                              int *nparams,
                              unsigned int flags)
7394
{
7395
    virQEMUDriverPtr driver = dom->conn->privateData;
7396 7397 7398
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
7399
    virDomainDefPtr persistentDef = NULL;
7400 7401 7402
    int ret = -1;
    int rc;

7403
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
7404 7405
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
7406

7407
    qemuDriverLock(driver);
7408

7409 7410 7411
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

7412
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
7413 7414

    if (vm == NULL) {
7415 7416
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
7417 7418 7419
        goto cleanup;
    }

7420 7421 7422
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
7423

7424
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7425
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
7426 7427
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup memory controller is not mounted"));
7428 7429 7430 7431
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7432 7433
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"), vm->def->name);
7434 7435 7436 7437
            goto cleanup;
        }
    }

7438 7439 7440 7441 7442 7443 7444
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

7445
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7446
        for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
7447 7448 7449 7450
            virMemoryParameterPtr param = &params[i];

            switch (i) {
            case 0: /* fill memory hard limit here */
7451 7452 7453 7454
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.hard_limit) < 0)
7455 7456 7457 7458
                    goto cleanup;
                break;

            case 1: /* fill memory soft limit here */
7459 7460 7461 7462
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.soft_limit) < 0)
7463 7464 7465 7466
                    goto cleanup;
                break;

            case 2: /* fill swap hard limit here */
7467 7468 7469 7470
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.swap_hard_limit) < 0)
7471 7472 7473 7474 7475 7476 7477 7478 7479
                    goto cleanup;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
7480 7481
    }

7482
    for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
7483
        virTypedParameterPtr param = &params[i];
7484
        unsigned long long val = 0;
7485

7486 7487 7488
        /* Coverity does not realize that if we get here, group is set.  */
        sa_assert(group);

7489
        switch (i) {
7490 7491 7492 7493 7494
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
7495
                goto cleanup;
7496
            }
7497 7498 7499
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
7500
                goto cleanup;
7501 7502 7503 7504 7505 7506 7507
            break;

        case 1: /* fill memory soft limit here */
            rc = virCgroupGetMemorySoftLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory soft limit"));
7508
                goto cleanup;
7509
            }
7510 7511 7512
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
7513
                goto cleanup;
7514 7515 7516
            break;

        case 2: /* fill swap hard limit here */
7517
            rc = virCgroupGetMemSwapHardLimit(group, &val);
7518 7519 7520
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
7521
                goto cleanup;
7522
            }
7523 7524 7525
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
7526
                goto cleanup;
7527 7528 7529 7530 7531 7532 7533 7534
            break;

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

7535
out:
7536 7537
    if (QEMU_NB_MEM_PARAM < *nparams)
        *nparams = QEMU_NB_MEM_PARAM;
7538 7539
    ret = 0;

7540 7541 7542 7543
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
7544
        virObjectUnlock(vm);
7545 7546 7547 7548
    qemuDriverUnlock(driver);
    return ret;
}

7549 7550 7551 7552 7553 7554
static int
qemuDomainSetNumaParameters(virDomainPtr dom,
                            virTypedParameterPtr params,
                            int nparams,
                            unsigned int flags)
{
7555
    virQEMUDriverPtr driver = dom->conn->privateData;
7556 7557 7558 7559 7560
    int i;
    virDomainDefPtr persistentDef = NULL;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
7561
    virQEMUDriverConfigPtr cfg = NULL;
7562 7563 7564

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
7565 7566 7567 7568 7569 7570 7571
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_NUMA_MODE,
                                       VIR_TYPED_PARAM_INT,
                                       VIR_DOMAIN_NUMA_NODESET,
                                       VIR_TYPED_PARAM_STRING,
                                       NULL) < 0)
        return -1;
7572 7573 7574

    qemuDriverLock(driver);

7575
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
7576 7577

    if (vm == NULL) {
7578 7579
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
7580 7581
        goto cleanup;
    }
7582
    cfg = virQEMUDriverGetConfig(driver);
7583 7584 7585 7586 7587 7588 7589

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUSET)) {
7590 7591
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup cpuset controller is not mounted"));
7592 7593 7594 7595
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7596 7597 7598
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"),
                           vm->def->name);
7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609
            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) {
7610 7611
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("can't change numa mode for running domain"));
7612 7613 7614 7615 7616 7617 7618 7619 7620
                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;
7621
            virBitmapPtr nodeset = NULL;
7622 7623
            char *nodeset_str = NULL;

7624 7625 7626
            if (virBitmapParse(params[i].value.s,
                               0, &nodeset,
                               VIR_DOMAIN_CPUMASK_LEN) < 0) {
7627 7628 7629 7630 7631
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to parse nodeset"));
                ret = -1;
                continue;
            }
7632 7633 7634 7635

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                if (vm->def->numatune.memory.mode !=
                    VIR_DOMAIN_NUMATUNE_MEM_STRICT) {
7636 7637 7638
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("change of nodeset for running domain "
                                     "requires strict numa mode"));
7639
                    virBitmapFree(nodeset);
7640 7641 7642
                    ret = -1;
                    continue;
                }
7643 7644

                /* Ensure the cpuset string is formated before passing to cgroup */
7645
                if (!(nodeset_str = virBitmapFormat(nodeset))) {
7646 7647
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Failed to format nodeset"));
7648
                    virBitmapFree(nodeset);
7649 7650 7651 7652 7653
                    ret = -1;
                    continue;
                }

                if ((rc = virCgroupSetCpusetMems(group, nodeset_str) != 0)) {
7654 7655
                    virReportSystemError(-rc, "%s",
                                         _("unable to set numa tunable"));
7656
                    virBitmapFree(nodeset);
7657
                    VIR_FREE(nodeset_str);
7658 7659 7660
                    ret = -1;
                    continue;
                }
7661
                VIR_FREE(nodeset_str);
7662 7663 7664

                /* update vm->def here so that dumpxml can read the new
                 * values from vm->def. */
7665
                virBitmapFree(vm->def->numatune.memory.nodemask);
7666

7667 7668
                vm->def->numatune.memory.placement_mode =
                    VIR_DOMAIN_NUMATUNE_MEM_PLACEMENT_MODE_STATIC;
7669
                vm->def->numatune.memory.nodemask = virBitmapNewCopy(nodeset);
7670 7671 7672
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7673
                virBitmapFree(persistentDef->numatune.memory.nodemask);
7674 7675

                persistentDef->numatune.memory.nodemask = nodeset;
7676 7677
                persistentDef->numatune.memory.placement_mode =
                    VIR_DOMAIN_NUMATUNE_MEM_PLACEMENT_MODE_STATIC;
7678
                nodeset = NULL;
7679
            }
7680
            virBitmapFree(nodeset);
7681 7682 7683 7684
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7685 7686 7687
        if (!persistentDef->numatune.memory.placement_mode)
            persistentDef->numatune.memory.placement_mode =
                VIR_DOMAIN_NUMATUNE_MEM_PLACEMENT_MODE_AUTO;
7688
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
7689 7690 7691 7692 7693 7694
            ret = -1;
    }

cleanup:
    virCgroupFree(&group);
    if (vm)
7695
        virObjectUnlock(vm);
7696
    qemuDriverUnlock(driver);
7697
    virObjectUnref(cfg);
7698 7699 7700 7701 7702 7703 7704 7705 7706
    return ret;
}

static int
qemuDomainGetNumaParameters(virDomainPtr dom,
                            virTypedParameterPtr params,
                            int *nparams,
                            unsigned int flags)
{
7707
    virQEMUDriverPtr driver = dom->conn->privateData;
7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr persistentDef = NULL;
    char *nodeset = NULL;
    int ret = -1;
    int rc;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    qemuDriverLock(driver);

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

7727
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
7728 7729

    if (vm == NULL) {
7730 7731
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if ((*nparams) == 0) {
        *nparams = QEMU_NB_NUMA_PARAM;
        ret = 0;
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
7747 7748
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup memory controller is not mounted"));
7749 7750 7751 7752
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7753 7754 7755
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"),
                           vm->def->name);
7756 7757 7758 7759 7760 7761 7762 7763 7764
            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 */
7765 7766
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_MODE,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
7767 7768 7769 7770 7771 7772 7773 7774 7775
                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) {
7776 7777
                nodeset = virBitmapFormat(persistentDef->numatune.memory.nodemask);
                if (!nodeset)
7778 7779 7780 7781 7782 7783 7784 7785 7786
                    nodeset = strdup("");
            } else {
                rc = virCgroupGetCpusetMems(group, &nodeset);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get numa nodeset"));
                    goto cleanup;
                }
            }
7787 7788
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_NODESET,
                                        VIR_TYPED_PARAM_STRING, nodeset) < 0)
7789
                goto cleanup;
S
Stefan Berger 已提交
7790 7791 7792

            nodeset = NULL;

7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805
            break;

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

    if (*nparams > QEMU_NB_NUMA_PARAM)
        *nparams = QEMU_NB_NUMA_PARAM;
    ret = 0;

cleanup:
S
Stefan Berger 已提交
7806
    VIR_FREE(nodeset);
7807 7808
    virCgroupFree(&group);
    if (vm)
7809
        virObjectUnlock(vm);
7810 7811 7812 7813
    qemuDriverUnlock(driver);
    return ret;
}

7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825
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 已提交
7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845
    /* If we does not know VCPU<->PID mapping or all vcpu runs in the same
     * thread, we cannot control each vcpu. So we only modify cpu bandwidth
     * when each vcpu has a separated thread.
     */
    if (priv->nvcpupids != 0 && priv->vcpupids[0] != vm->pid) {
        for (i = 0; i < priv->nvcpupids; i++) {
            rc = virCgroupForVcpu(cgroup, i, &cgroup_vcpu, 0);
            if (rc < 0) {
                virReportSystemError(-rc,
                                     _("Unable to find vcpu cgroup for %s(vcpu:"
                                       " %d)"),
                                     vm->def->name, i);
                goto cleanup;
            }

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

            virCgroupFree(&cgroup_vcpu);
        }
7846 7847 7848 7849 7850 7851 7852 7853 7854
    }

    return 0;

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

7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888
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;
    }

    rc = virCgroupForEmulator(cgroup, &cgroup_emulator, 0);
    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;
}

7889 7890 7891 7892 7893 7894 7895 7896 7897
#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;                                                       \
    }

7898 7899 7900 7901 7902
static int
qemuSetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int nparams,
                                unsigned int flags)
7903
{
7904
    virQEMUDriverPtr driver = dom->conn->privateData;
7905 7906 7907
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
7908
    virDomainDefPtr vmdef = NULL;
7909 7910
    unsigned long long value_ul;
    long long value_l;
7911
    int ret = -1;
7912
    int rc;
7913
    virQEMUDriverConfigPtr cfg = NULL;
7914

7915 7916
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
7917 7918 7919 7920 7921 7922 7923
    if (virTypedParameterArrayValidate(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,
7924 7925 7926 7927
                                       VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA,
                                       VIR_TYPED_PARAM_LLONG,
7928 7929
                                       NULL) < 0)
        return -1;
7930

7931
    qemuDriverLock(driver);
7932

7933
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
7934 7935

    if (vm == NULL) {
7936 7937
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
7938 7939 7940
        goto cleanup;
    }

7941 7942
    cfg = virQEMUDriverGetConfig(driver);

7943 7944 7945
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &vmdef) < 0)
        goto cleanup;
7946

7947 7948 7949 7950 7951
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto cleanup;
7952 7953
    }

7954
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7955
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
7956 7957
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup CPU controller is not mounted"));
7958 7959 7960
            goto cleanup;
        }
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7961 7962 7963
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot find cgroup for domain %s"),
                           vm->def->name);
7964 7965 7966 7967
            goto cleanup;
        }
    }

7968
    for (i = 0; i < nparams; i++) {
7969
        virTypedParameterPtr param = &params[i];
7970 7971
        value_ul = param->value.ul;
        value_l = param->value.l;
7972

7973
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CPU_SHARES)) {
7974
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7975
                if ((rc = virCgroupSetCpuShares(group, value_ul))) {
7976 7977 7978 7979
                    virReportSystemError(-rc, "%s",
                                         _("unable to set cpu shares tunable"));
                    goto cleanup;
                }
7980
                vm->def->cputune.shares = value_ul;
7981
            }
7982

7983 7984 7985
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.shares = value_ul;

7986
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD)) {
7987 7988 7989
            SCHED_RANGE_CHECK(value_ul, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                              QEMU_SCHED_MIN_PERIOD, QEMU_SCHED_MAX_PERIOD);

7990 7991
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_ul) {
                if ((rc = qemuSetVcpusBWLive(vm, group, value_ul, 0)))
7992
                    goto cleanup;
7993

7994
                vm->def->cputune.period = value_ul;
7995 7996
            }

7997
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
7998
                vmdef->cputune.period = params[i].value.ul;
7999

8000
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA)) {
8001 8002 8003
            SCHED_RANGE_CHECK(value_l, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                              QEMU_SCHED_MIN_QUOTA, QEMU_SCHED_MAX_QUOTA);

8004 8005
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_l) {
                if ((rc = qemuSetVcpusBWLive(vm, group, 0, value_l)))
8006
                    goto cleanup;
8007

8008
                vm->def->cputune.quota = value_l;
8009 8010
            }

8011 8012 8013
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.quota = value_l;

8014
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD)) {
8015 8016 8017
            SCHED_RANGE_CHECK(value_ul, VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD,
                              QEMU_SCHED_MIN_PERIOD, QEMU_SCHED_MAX_PERIOD);

8018 8019
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_ul) {
                if ((rc = qemuSetEmulatorBandwidthLive(vm, group, value_ul, 0)))
8020 8021
                    goto cleanup;

8022
                vm->def->cputune.emulator_period = value_ul;
8023 8024
            }

8025 8026 8027
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.emulator_period = value_ul;

8028
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA)) {
8029 8030 8031
            SCHED_RANGE_CHECK(value_l, VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA,
                              QEMU_SCHED_MIN_QUOTA, QEMU_SCHED_MAX_QUOTA);

8032 8033
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_l) {
                if ((rc = qemuSetEmulatorBandwidthLive(vm, group, 0, value_l)))
8034 8035
                    goto cleanup;

8036
                vm->def->cputune.emulator_quota = value_l;
8037 8038
            }

8039 8040
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.emulator_quota = value_l;
8041 8042
        }
    }
8043

8044
    if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0)
8045 8046 8047 8048
        goto cleanup;


    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8049
        rc = virDomainSaveConfig(cfg->configDir, vmdef);
8050 8051 8052
        if (rc < 0)
            goto cleanup;

8053
        virDomainObjAssignDef(vm, vmdef, false, NULL);
8054 8055 8056
        vmdef = NULL;
    }

8057 8058 8059
    ret = 0;

cleanup:
8060
    virDomainDefFree(vmdef);
8061 8062
    virCgroupFree(&group);
    if (vm)
8063
        virObjectUnlock(vm);
8064
    qemuDriverUnlock(driver);
8065
    virObjectUnref(cfg);
8066 8067
    return ret;
}
8068
#undef SCHED_RANGE_CHECK
8069

8070 8071 8072 8073
static int
qemuSetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int nparams)
8074 8075 8076 8077
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
8078
                                           VIR_DOMAIN_AFFECT_CURRENT);
8079 8080
}

8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145
static int
qemuGetVcpuBWLive(virCgroupPtr cgroup, unsigned long long *period,
                  long long *quota)
{
    int rc;

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

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

    return 0;
}

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

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

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

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

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

out:
    ret = 0;

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

8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182
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 */
    rc = virCgroupForEmulator(cgroup, &cgroup_emulator, 0);
    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;
}

8183 8184 8185 8186 8187
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
8188
{
8189
    virQEMUDriverPtr driver = dom->conn->privateData;
8190 8191
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
8192 8193 8194
    unsigned long long shares;
    unsigned long long period;
    long long quota;
8195 8196
    unsigned long long emulator_period;
    long long emulator_quota;
8197 8198
    int ret = -1;
    int rc;
8199
    bool cpu_bw_status = false;
8200
    int saved_nparams = 0;
8201
    virDomainDefPtr persistentDef;
8202

8203
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
8204 8205
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
8206

8207 8208
    qemuDriverLock(driver);

8209 8210 8211
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

8212 8213 8214 8215 8216 8217 8218
    if (*nparams > 1) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

8219
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
8220 8221

    if (vm == NULL) {
8222 8223
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
8224 8225 8226
        goto cleanup;
    }

8227 8228 8229
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
8230

8231
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8232 8233 8234 8235
        shares = persistentDef->cputune.shares;
        if (*nparams > 1 && cpu_bw_status) {
            period = persistentDef->cputune.period;
            quota = persistentDef->cputune.quota;
8236 8237
            emulator_period = persistentDef->cputune.emulator_period;
            emulator_quota = persistentDef->cputune.emulator_quota;
8238
        }
8239
        goto out;
8240 8241
    }

8242
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
8243 8244
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cgroup CPU controller is not mounted"));
8245 8246 8247
        goto cleanup;
    }

8248
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
8249 8250
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find cgroup for domain %s"), vm->def->name);
8251 8252 8253
        goto cleanup;
    }

8254
    rc = virCgroupGetCpuShares(group, &shares);
8255
    if (rc != 0) {
8256
        virReportSystemError(-rc, "%s",
8257 8258 8259
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
8260 8261 8262 8263 8264 8265

    if (*nparams > 1 && cpu_bw_status) {
        rc = qemuGetVcpusBWLive(vm, group, &period, &quota);
        if (rc != 0)
            goto cleanup;
    }
8266 8267 8268 8269 8270 8271 8272 8273

    if (*nparams > 3 && cpu_bw_status) {
        rc = qemuGetEmulatorBandwidthLive(vm, group, &emulator_period,
                                          &emulator_quota);
        if (rc != 0)
            goto cleanup;
    }

8274
out:
8275 8276
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CPU_SHARES,
                                VIR_TYPED_PARAM_ULLONG, shares) < 0)
C
Chris Lalancette 已提交
8277
        goto cleanup;
8278 8279 8280 8281
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
8282 8283 8284
            if (virTypedParameterAssign(&params[1],
                                        VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                                        VIR_TYPED_PARAM_ULLONG, period) < 0)
8285 8286 8287 8288 8289
                goto cleanup;
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
8290 8291 8292
            if (virTypedParameterAssign(&params[2],
                                        VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                                        VIR_TYPED_PARAM_LLONG, quota) < 0)
8293 8294 8295
                goto cleanup;
            saved_nparams++;
        }
8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313

        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++;
        }
8314 8315 8316 8317
    }

    *nparams = saved_nparams;

8318 8319 8320 8321 8322
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
8323
        virObjectUnlock(vm);
8324
    qemuDriverUnlock(driver);
8325 8326 8327
    return ret;
}

8328 8329 8330 8331 8332 8333
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
8334
                                           VIR_DOMAIN_AFFECT_CURRENT);
8335
}
8336

8337 8338 8339 8340 8341 8342 8343
/**
 * 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 已提交
8344 8345 8346 8347
qemuDomainBlockResize(virDomainPtr dom,
                      const char *path,
                      unsigned long long size,
                      unsigned int flags)
8348
{
8349
    virQEMUDriverPtr driver = dom->conn->privateData;
8350 8351 8352 8353 8354 8355
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1, i;
    char *device = NULL;
    virDomainDiskDefPtr disk = NULL;

E
Eric Blake 已提交
8356
    virCheckFlags(VIR_DOMAIN_BLOCK_RESIZE_BYTES, -1);
8357 8358

    if (path[0] == '\0') {
8359 8360
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("empty path"));
8361 8362 8363
        return -1;
    }

E
Eric Blake 已提交
8364 8365 8366
    /* We prefer operating on bytes.  */
    if ((flags & VIR_DOMAIN_BLOCK_RESIZE_BYTES) == 0) {
        if (size > ULLONG_MAX / 1024) {
8367 8368 8369
            virReportError(VIR_ERR_OVERFLOW,
                           _("size must be less than %llu"),
                           ULLONG_MAX / 1024);
E
Eric Blake 已提交
8370 8371 8372
            return -1;
        }
        size *= 1024;
8373 8374
    }

8375
    if (!(vm = qemuDomObjFromDomain(dom)))
8376 8377 8378 8379 8380 8381 8382 8383
        goto cleanup;

    priv = vm->privateData;

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

    if (!virDomainObjIsActive(vm)) {
8384 8385
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8386 8387 8388 8389
        goto endjob;
    }

    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
8390 8391
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path: %s"), path);
8392
        goto endjob;
8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417
    }
    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)
8418
        virObjectUnlock(vm);
8419 8420 8421
    return ret;
}

8422 8423 8424 8425 8426
/* 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
8427 8428 8429
qemuDomainBlockStats(virDomainPtr dom,
                     const char *path,
                     struct _virDomainBlockStats *stats)
8430
{
8431
    virQEMUDriverPtr driver = dom->conn->privateData;
8432
    int i, ret = -1;
8433
    virDomainObjPtr vm;
8434
    virDomainDiskDefPtr disk = NULL;
8435
    qemuDomainObjPrivatePtr priv;
8436

8437
    if (!(vm = qemuDomObjFromDomain(dom)))
8438
        goto cleanup;
8439

8440
    if (!virDomainObjIsActive(vm)) {
8441 8442
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8443 8444 8445
        goto cleanup;
    }

8446
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
8447 8448
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path: %s"), path);
8449
        goto cleanup;
8450
    }
8451
    disk = vm->def->disks[i];
8452

8453
    if (!disk->info.alias) {
8454 8455
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing disk device alias name for %s"), disk->dst);
8456
        goto cleanup;
8457
    }
8458

8459
    priv = vm->privateData;
8460 8461
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
8462

8463
    if (!virDomainObjIsActive(vm)) {
8464 8465
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8466 8467
        goto endjob;
    }
8468

8469
    qemuDomainObjEnterMonitor(driver, vm);
8470 8471 8472 8473
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
8474
                                       NULL,
8475 8476
                                       &stats->wr_req,
                                       &stats->wr_bytes,
8477 8478 8479
                                       NULL,
                                       NULL,
                                       NULL,
8480 8481
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
8482

8483
endjob:
8484 8485
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8486

8487
cleanup:
8488
    if (vm)
8489
        virObjectUnlock(vm);
8490
    return ret;
8491 8492
}

8493
static int
8494 8495 8496 8497 8498
qemuDomainBlockStatsFlags(virDomainPtr dom,
                          const char *path,
                          virTypedParameterPtr params,
                          int *nparams,
                          unsigned int flags)
8499
{
8500
    virQEMUDriverPtr driver = dom->conn->privateData;
8501 8502 8503 8504 8505 8506
    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;
8507
    virTypedParameterPtr param;
8508

8509 8510 8511 8512
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;
8513

8514
    if (!(vm = qemuDomObjFromDomain(dom)))
8515 8516 8517
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
8518 8519
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8520 8521 8522 8523
        goto cleanup;
    }

    if (*nparams != 0) {
8524
        if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
8525 8526
            virReportError(VIR_ERR_INVALID_ARG,
                           _("invalid path: %s"), path);
8527 8528
            goto cleanup;
        }
8529
        disk = vm->def->disks[i];
8530 8531

        if (!disk->info.alias) {
8532 8533 8534
             virReportError(VIR_ERR_INTERNAL_ERROR,
                            _("missing disk device alias name for %s"),
                            disk->dst);
8535 8536 8537 8538 8539 8540 8541 8542 8543 8544
             goto cleanup;
        }
    }

    priv = vm->privateData;
    VIR_DEBUG("priv=%p, params=%p, flags=%x", priv, params, flags);

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

8545
    if (!virDomainObjIsActive(vm)) {
8546 8547
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8548 8549 8550
        goto endjob;
    }

8551 8552 8553 8554
    qemuDomainObjEnterMonitor(driver, vm);
    tmp = *nparams;
    ret = qemuMonitorGetBlockStatsParamsNumber(priv->mon, nparams);

8555
    if (tmp == 0 || ret < 0) {
8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576
        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;

8577 8578
    tmp = 0;
    ret = -1;
8579

8580 8581
    if (tmp < *nparams && wr_bytes != -1) {
        param = &params[tmp];
8582 8583
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES,
                                    VIR_TYPED_PARAM_LLONG, wr_bytes) < 0)
8584 8585 8586
            goto endjob;
        tmp++;
    }
8587

8588
    if (tmp < *nparams && wr_req != -1) {
8589
        param = &params[tmp];
8590 8591
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_WRITE_REQ,
                                    VIR_TYPED_PARAM_LLONG, wr_req) < 0)
8592 8593 8594
            goto endjob;
        tmp++;
    }
8595

8596
    if (tmp < *nparams && rd_bytes != -1) {
8597
        param = &params[tmp];
8598 8599
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_READ_BYTES,
                                    VIR_TYPED_PARAM_LLONG, rd_bytes) < 0)
8600 8601 8602
            goto endjob;
        tmp++;
    }
8603

8604
    if (tmp < *nparams && rd_req != -1) {
8605
        param = &params[tmp];
8606 8607
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_READ_REQ,
                                    VIR_TYPED_PARAM_LLONG, rd_req) < 0)
8608 8609 8610
            goto endjob;
        tmp++;
    }
8611

8612
    if (tmp < *nparams && flush_req != -1) {
8613
        param = &params[tmp];
8614 8615
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ,
                                    VIR_TYPED_PARAM_LLONG, flush_req) < 0)
8616 8617 8618
            goto endjob;
        tmp++;
    }
8619

8620
    if (tmp < *nparams && wr_total_times != -1) {
8621
        param = &params[tmp];
8622 8623 8624
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG, wr_total_times) < 0)
8625 8626 8627
            goto endjob;
        tmp++;
    }
8628

8629
    if (tmp < *nparams && rd_total_times != -1) {
8630
        param = &params[tmp];
8631 8632 8633
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG, rd_total_times) < 0)
8634 8635 8636
            goto endjob;
        tmp++;
    }
8637

8638
    if (tmp < *nparams && flush_total_times != -1) {
8639
        param = &params[tmp];
8640 8641 8642 8643
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_FLUSH_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG,
                                    flush_total_times) < 0)
8644 8645
            goto endjob;
        tmp++;
8646 8647
    }

8648 8649 8650 8651 8652
    /* Field 'errs' is meaningless for QEMU, won't set it. */

    ret = 0;
    *nparams = tmp;

8653 8654 8655 8656 8657 8658
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    if (vm)
8659
        virObjectUnlock(vm);
8660 8661 8662
    return ret;
}

8663
#ifdef __linux__
8664
static int
8665 8666 8667
qemuDomainInterfaceStats(virDomainPtr dom,
                         const char *path,
                         struct _virDomainInterfaceStats *stats)
8668
{
8669
    virDomainObjPtr vm;
8670
    int i;
8671
    int ret = -1;
8672

8673
    if (!(vm = qemuDomObjFromDomain(dom)))
8674
        goto cleanup;
8675

D
Daniel P. Berrange 已提交
8676
    if (!virDomainObjIsActive(vm)) {
8677 8678
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8679
        goto cleanup;
8680 8681 8682
    }

    /* Check the path is one of the domain's network interfaces. */
8683 8684
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
8685
            STREQ(vm->def->nets[i]->ifname, path)) {
8686 8687 8688
            ret = 0;
            break;
        }
8689 8690
    }

8691
    if (ret == 0)
8692
        ret = linuxDomainInterfaceStats(path, stats);
8693
    else
8694 8695
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path, '%s' is not a known interface"), path);
8696

8697
cleanup:
8698
    if (vm)
8699
        virObjectUnlock(vm);
8700 8701
    return ret;
}
8702
#else
8703
static int
E
Eric Blake 已提交
8704
qemuDomainInterfaceStats(virDomainPtr dom ATTRIBUTE_UNUSED,
8705 8706
                         const char *path ATTRIBUTE_UNUSED,
                         struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
8707
{
8708 8709
    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("interface stats not implemented on this platform"));
8710 8711
    return -1;
}
8712
#endif
8713

8714 8715 8716 8717 8718 8719 8720
static int
qemuDomainSetInterfaceParameters(virDomainPtr dom,
                                 const char *device,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 unsigned int flags)
{
8721
    virQEMUDriverPtr driver = dom->conn->privateData;
8722 8723 8724 8725 8726 8727
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr persistentDef = NULL;
    int ret = -1;
    virDomainNetDefPtr net = NULL, persistentNet = NULL;
8728
    virNetDevBandwidthPtr bandwidth = NULL, newBandwidth = NULL;
8729
    virQEMUDriverConfigPtr cfg = NULL;
8730 8731 8732

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747
    if (virTypedParameterArrayValidate(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)
        return -1;
8748

8749
    qemuDriverLock(driver);
8750
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
8751 8752

    if (vm == NULL) {
8753 8754
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
8755 8756 8757
        goto cleanup;
    }

8758 8759
    cfg = virQEMUDriverGetConfig(driver);

8760 8761 8762 8763 8764 8765 8766
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        net = virDomainNetFind(vm->def, device);
        if (!net) {
8767 8768
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Can't find device %s"), device);
8769 8770 8771 8772 8773 8774
            goto cleanup;
        }
    }
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        persistentNet = virDomainNetFind(persistentDef, device);
        if (!persistentNet) {
8775 8776
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Can't find device %s"), device);
8777 8778 8779 8780
            goto cleanup;
        }
    }

8781 8782 8783
    if ((VIR_ALLOC(bandwidth) < 0) ||
        (VIR_ALLOC(bandwidth->in) < 0) ||
        (VIR_ALLOC(bandwidth->out) < 0)) {
8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805
        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;
        }
    }

8806
    /* average is mandatory, peak and burst are optional. So if no
8807
     * average is given, we free inbound/outbound here which causes
8808
     * inbound/outbound to not be set. */
8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823
    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
8824
         * here to prevent them from being lost. */
8825 8826
        if (bandwidth->in ||
            (net->bandwidth && net->bandwidth->in)) {
8827 8828 8829 8830
            if (VIR_ALLOC(newBandwidth->in) < 0) {
                virReportOOMError();
                goto cleanup;
            }
8831 8832 8833 8834 8835 8836 8837

            memcpy(newBandwidth->in,
                   bandwidth->in ? bandwidth->in : net->bandwidth->in,
                   sizeof(*newBandwidth->in));
        }
        if (bandwidth->out ||
            (net->bandwidth && net->bandwidth->out)) {
8838 8839 8840 8841
            if (VIR_ALLOC(newBandwidth->out) < 0) {
                virReportOOMError();
                goto cleanup;
            }
8842 8843 8844 8845

            memcpy(newBandwidth->out,
                   bandwidth->out ? bandwidth->out : net->bandwidth->out,
                   sizeof(*newBandwidth->out));
8846 8847
        }

8848
        if (virNetDevBandwidthSet(net->ifname, newBandwidth, false) < 0) {
8849 8850 8851
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot set bandwidth limits on %s"),
                           device);
8852 8853 8854 8855 8856
            goto cleanup;
        }

        virNetDevBandwidthFree(net->bandwidth);
        net->bandwidth = newBandwidth;
E
Eric Blake 已提交
8857
        newBandwidth = NULL;
8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875
    }
    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;
            }
        }

8876
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
8877 8878 8879 8880 8881 8882
            goto cleanup;
    }

    ret = 0;
cleanup:
    virNetDevBandwidthFree(bandwidth);
8883
    virNetDevBandwidthFree(newBandwidth);
8884 8885
    virCgroupFree(&group);
    if (vm)
8886
        virObjectUnlock(vm);
8887
    qemuDriverUnlock(driver);
8888
    virObjectUnref(cfg);
8889 8890 8891 8892 8893 8894 8895 8896 8897 8898
    return ret;
}

static int
qemuDomainGetInterfaceParameters(virDomainPtr dom,
                                 const char *device,
                                 virTypedParameterPtr params,
                                 int *nparams,
                                 unsigned int flags)
{
8899
    virQEMUDriverPtr driver = dom->conn->privateData;
8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainDefPtr persistentDef = NULL;
    virDomainNetDefPtr net = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    qemuDriverLock(driver);

    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

8916
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
8917 8918

    if (vm == NULL) {
8919 8920
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &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) {
8940 8941
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Can't find device %s"), device);
8942 8943 8944 8945
        goto cleanup;
    }

    for (i = 0; i < *nparams && i < QEMU_NB_BANDWIDTH_PARAM; i++) {
8946
        switch (i) {
8947
        case 0: /* inbound.average */
8948 8949 8950
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_AVERAGE,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
8951 8952 8953 8954 8955
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->average;
            break;
        case 1: /* inbound.peak */
8956 8957 8958
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_PEAK,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
8959 8960 8961 8962 8963
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->peak;
            break;
        case 2: /* inbound.burst */
8964 8965 8966
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_BURST,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
8967 8968 8969 8970 8971
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->burst;
            break;
        case 3: /* outbound.average */
8972 8973 8974
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
8975 8976 8977 8978 8979
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->average;
            break;
        case 4: /* outbound.peak */
8980 8981 8982
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_PEAK,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
8983 8984 8985 8986 8987
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->peak;
            break;
        case 5: /* outbound.burst */
8988 8989 8990
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_BURST,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008
                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 (group)
        virCgroupFree(&group);
    if (vm)
9009
        virObjectUnlock(vm);
9010 9011 9012 9013
    qemuDriverUnlock(driver);
    return ret;
}

9014
static int
9015 9016 9017 9018
qemuDomainMemoryStats(virDomainPtr dom,
                      struct _virDomainMemoryStat *stats,
                      unsigned int nr_stats,
                      unsigned int flags)
9019
{
9020
    virQEMUDriverPtr driver = dom->conn->privateData;
9021
    virDomainObjPtr vm;
M
Martin Kletzander 已提交
9022
    int ret = -1;
9023

9024 9025
    virCheckFlags(0, -1);

9026
    if (!(vm = qemuDomObjFromDomain(dom)))
9027 9028
        goto cleanup;

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

M
Martin Kletzander 已提交
9032
    if (!virDomainObjIsActive(vm)) {
9033 9034
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
M
Martin Kletzander 已提交
9035
    } else {
9036
        qemuDomainObjPrivatePtr priv = vm->privateData;
9037
        qemuDomainObjEnterMonitor(driver, vm);
9038
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
9039
        qemuDomainObjExitMonitor(driver, vm);
M
Martin Kletzander 已提交
9040 9041 9042

        if (ret >= 0 && ret < nr_stats) {
            long rss;
9043
            if (qemuGetProcessInfo(NULL, NULL, &rss, vm->pid, 0) < 0) {
9044 9045
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("cannot get RSS for domain"));
M
Martin Kletzander 已提交
9046 9047 9048 9049 9050 9051 9052
            } else {
                stats[ret].tag = VIR_DOMAIN_MEMORY_STAT_RSS;
                stats[ret].val = rss;
                ret++;
            }

        }
9053 9054
    }

9055
    if (qemuDomainObjEndJob(driver, vm) == 0)
9056 9057
        vm = NULL;

9058 9059
cleanup:
    if (vm)
9060
        virObjectUnlock(vm);
9061 9062 9063
    return ret;
}

9064
static int
9065 9066 9067 9068 9069
qemuDomainBlockPeek(virDomainPtr dom,
                    const char *path,
                    unsigned long long offset, size_t size,
                    void *buffer,
                    unsigned int flags)
9070
{
9071
    virDomainObjPtr vm;
9072 9073
    int fd = -1, ret = -1;
    const char *actual;
9074

E
Eric Blake 已提交
9075 9076
    virCheckFlags(0, -1);

9077
    if (!(vm = qemuDomObjFromDomain(dom)))
9078
        goto cleanup;
9079 9080

    if (!path || path[0] == '\0') {
9081 9082
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("NULL or empty path"));
9083
        goto cleanup;
9084 9085
    }

9086 9087
    /* Check the path belongs to this domain.  */
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
9088 9089
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path '%s'"), path);
9090
        goto cleanup;
9091
    }
9092
    path = actual;
9093

9094 9095 9096 9097 9098 9099 9100
    /* 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;
    }
9101

9102 9103 9104 9105 9106 9107 9108 9109 9110
    /* 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;
9111 9112
    }

9113 9114
    ret = 0;

9115
cleanup:
9116
    VIR_FORCE_CLOSE(fd);
9117
    if (vm)
9118
        virObjectUnlock(vm);
9119 9120 9121
    return ret;
}

R
Richard W.M. Jones 已提交
9122
static int
9123 9124 9125 9126
qemuDomainMemoryPeek(virDomainPtr dom,
                     unsigned long long offset, size_t size,
                     void *buffer,
                     unsigned int flags)
R
Richard W.M. Jones 已提交
9127
{
9128
    virQEMUDriverPtr driver = dom->conn->privateData;
9129
    virDomainObjPtr vm;
9130
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
9131
    int fd = -1, ret = -1;
9132
    qemuDomainObjPrivatePtr priv;
9133
    virQEMUDriverConfigPtr cfg = NULL;
R
Richard W.M. Jones 已提交
9134

9135 9136
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

9137
    if (!(vm = qemuDomObjFromDomain(dom)))
9138 9139
        goto cleanup;

9140 9141
    cfg = virQEMUDriverGetConfig(driver);

9142
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
9143 9144
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
9145
        goto cleanup;
R
Richard W.M. Jones 已提交
9146 9147
    }

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

D
Daniel P. Berrange 已提交
9151
    if (!virDomainObjIsActive(vm)) {
9152 9153
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
9154
        goto endjob;
R
Richard W.M. Jones 已提交
9155 9156
    }

9157
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", cfg->cacheDir) < 0) {
9158
        virReportOOMError();
9159
        goto endjob;
9160 9161
    }

R
Richard W.M. Jones 已提交
9162
    /* Create a temporary filename. */
9163
    if ((fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
9164
        virReportSystemError(errno,
9165
                             _("mkostemp(\"%s\") failed"), tmp);
9166
        goto endjob;
R
Richard W.M. Jones 已提交
9167 9168
    }

9169
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
9170

9171
    priv = vm->privateData;
9172
    qemuDomainObjEnterMonitor(driver, vm);
9173
    if (flags == VIR_MEMORY_VIRTUAL) {
9174
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
9175
            qemuDomainObjExitMonitor(driver, vm);
9176
            goto endjob;
9177
        }
9178
    } else {
9179
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
9180
            qemuDomainObjExitMonitor(driver, vm);
9181
            goto endjob;
9182
        }
R
Richard W.M. Jones 已提交
9183
    }
9184
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
9185 9186

    /* Read the memory file into buffer. */
9187
    if (saferead(fd, buffer, size) == (ssize_t) -1) {
9188 9189 9190
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
9191
        goto endjob;
R
Richard W.M. Jones 已提交
9192 9193 9194
    }

    ret = 0;
9195

9196
endjob:
9197
    if (qemuDomainObjEndJob(driver, vm) == 0)
9198
        vm = NULL;
9199

9200
cleanup:
9201
    VIR_FORCE_CLOSE(fd);
9202 9203
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
9204
    VIR_FREE(tmp);
9205
    if (vm)
9206
        virObjectUnlock(vm);
9207
    virObjectUnref(cfg);
R
Richard W.M. Jones 已提交
9208 9209 9210
    return ret;
}

9211

9212 9213 9214 9215
static int qemuDomainGetBlockInfo(virDomainPtr dom,
                                  const char *path,
                                  virDomainBlockInfoPtr info,
                                  unsigned int flags) {
9216
    virQEMUDriverPtr driver = dom->conn->privateData;
9217 9218 9219 9220
    virDomainObjPtr vm;
    int ret = -1;
    int fd = -1;
    off_t end;
9221
    virStorageFileMetadata *meta = NULL;
9222
    virDomainDiskDefPtr disk = NULL;
9223
    struct stat sb;
9224
    int i;
9225
    int format;
9226
    virQEMUDriverConfigPtr cfg = NULL;
9227 9228 9229

    virCheckFlags(0, -1);

9230
    if (!(vm = qemuDomObjFromDomain(dom)))
9231 9232
        goto cleanup;

9233 9234
    cfg = virQEMUDriverGetConfig(driver);

9235
    if (!path || path[0] == '\0') {
9236 9237
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("NULL or empty path"));
9238 9239 9240 9241
        goto cleanup;
    }

    /* Check the path belongs to this domain. */
9242
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
9243 9244
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path %s not assigned to domain"), path);
9245 9246
        goto cleanup;
    }
9247 9248
    disk = vm->def->disks[i];
    if (!disk->src) {
9249 9250 9251
        virReportError(VIR_ERR_INVALID_ARG,
                       _("disk %s does not currently have a source assigned"),
                       path);
9252 9253 9254
        goto cleanup;
    }
    path = disk->src;
9255 9256

    /* The path is correct, now try to open it and get its size. */
9257
    fd = open(path, O_RDONLY);
9258 9259 9260 9261 9262 9263 9264
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
9265 9266
    if (disk->format) {
        format = disk->format;
9267
    } else {
9268 9269 9270 9271
        if (cfg->allowDiskFormatProbing) {
            if ((format = virStorageFileProbeFormat(disk->src,
                                                    cfg->user,
                                                    cfg->group)) < 0)
9272 9273
                goto cleanup;
        } else {
9274 9275 9276
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no disk format for %s and probing is disabled"),
                           disk->src);
9277
            goto cleanup;
9278
        }
9279 9280
    }

9281
    if (!(meta = virStorageFileGetMetadataFromFD(path, fd, format)))
9282 9283 9284 9285 9286 9287 9288 9289 9290 9291
        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)) {
9292
#ifndef WIN32
9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305
        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.
         */
9306
        end = lseek(fd, 0, SEEK_END);
9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317
        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 */
9318 9319
    if (meta->capacity)
        info->capacity = meta->capacity;
9320

9321
    /* Set default value .. */
9322 9323
    info->allocation = info->physical;

9324 9325 9326
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
9327
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
9328
        format != VIR_STORAGE_FILE_RAW &&
9329 9330
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
9331
        qemuDomainObjPrivatePtr priv = vm->privateData;
9332

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

9336
        if (virDomainObjIsActive(vm)) {
9337
            qemuDomainObjEnterMonitor(driver, vm);
9338 9339 9340 9341
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
9342
        } else {
9343
            ret = 0;
9344
        }
9345 9346 9347

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
9348 9349 9350
    } else {
        ret = 0;
    }
9351 9352

cleanup:
9353
    virStorageFileFreeMetadata(meta);
9354
    VIR_FORCE_CLOSE(fd);
9355
    if (vm)
9356
        virObjectUnlock(vm);
9357
    virObjectUnref(cfg);
9358 9359 9360 9361
    return ret;
}


9362
static int
9363 9364 9365 9366
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
9367
{
9368
    virQEMUDriverPtr driver = conn->privateData;
9369 9370
    int ret;

9371
    qemuDriverLock(driver);
9372 9373 9374
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
9375
    qemuDriverUnlock(driver);
9376

9377
    return ret;
9378 9379
}

9380

9381
static int
9382 9383
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
9384
{
9385
    virQEMUDriverPtr driver = conn->privateData;
9386 9387
    int ret;

9388
    qemuDriverLock(driver);
9389 9390 9391
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
9392
    qemuDriverUnlock(driver);
9393

9394
    return ret;
9395 9396
}

9397 9398 9399 9400 9401 9402 9403 9404 9405

static int
qemuDomainEventRegisterAny(virConnectPtr conn,
                           virDomainPtr dom,
                           int eventID,
                           virConnectDomainEventGenericCallback callback,
                           void *opaque,
                           virFreeCallback freecb)
{
9406
    virQEMUDriverPtr driver = conn->privateData;
9407 9408 9409
    int ret;

    qemuDriverLock(driver);
9410 9411 9412 9413
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID,
                                      callback, opaque, freecb, &ret) < 0)
9414
        ret = -1;
9415 9416 9417 9418 9419 9420 9421 9422 9423 9424
    qemuDriverUnlock(driver);

    return ret;
}


static int
qemuDomainEventDeregisterAny(virConnectPtr conn,
                             int callbackID)
{
9425
    virQEMUDriverPtr driver = conn->privateData;
9426 9427 9428
    int ret;

    qemuDriverLock(driver);
9429 9430 9431
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
9432 9433 9434 9435 9436 9437
    qemuDriverUnlock(driver);

    return ret;
}


9438 9439 9440
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
9441

C
Chris Lalancette 已提交
9442 9443 9444 9445 9446 9447
/* 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
9448 9449 9450 9451 9452 9453
qemuDomainMigratePrepareTunnel(virConnectPtr dconn,
                               virStreamPtr st,
                               unsigned long flags,
                               const char *dname,
                               unsigned long resource ATTRIBUTE_UNUSED,
                               const char *dom_xml)
C
Chris Lalancette 已提交
9454
{
9455
    virQEMUDriverPtr driver = dconn->privateData;
C
Chris Lalancette 已提交
9456
    int ret = -1;
9457

9458
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
9459

9460 9461
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
9462
    if (!dom_xml) {
9463 9464
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
9465 9466 9467
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
9468 9469
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
C
Chris Lalancette 已提交
9470 9471 9472
        goto cleanup;
    }
    if (st == NULL) {
9473 9474
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
9475 9476 9477
        goto cleanup;
    }

9478
    if (virLockManagerPluginUsesState(driver->lockManager)) {
9479 9480 9481
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot use migrate v2 protocol with lock manager %s"),
                       virLockManagerPluginGetName(driver->lockManager));
9482 9483 9484
        goto cleanup;
    }

9485 9486
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
L
liguang 已提交
9487
                                     st, dname, dom_xml, flags);
9488

C
Chris Lalancette 已提交
9489
cleanup:
9490
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
9491 9492 9493
    return ret;
}

D
Daniel Veillard 已提交
9494 9495 9496 9497
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
9498
static int ATTRIBUTE_NONNULL(5)
9499 9500 9501 9502 9503 9504 9505 9506 9507
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 已提交
9508
{
9509
    virQEMUDriverPtr driver = dconn->privateData;
9510
    int ret = -1;
9511

9512
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
9513

9514
    *uri_out = NULL;
D
Daniel Veillard 已提交
9515

9516
    qemuDriverLock(driver);
9517 9518

    if (virLockManagerPluginUsesState(driver->lockManager)) {
9519 9520 9521
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot use migrate v2 protocol with lock manager %s"),
                       virLockManagerPluginGetName(driver->lockManager));
9522 9523 9524
        goto cleanup;
    }

C
Chris Lalancette 已提交
9525 9526 9527 9528
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
9529 9530
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
9531 9532 9533
        goto cleanup;
    }

D
Daniel Veillard 已提交
9534
    if (!dom_xml) {
9535 9536
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no domain XML passed"));
9537
        goto cleanup;
D
Daniel Veillard 已提交
9538 9539
    }

9540 9541 9542 9543
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
9544
    ret = qemuMigrationPrepareDirect(driver, dconn,
9545
                                     NULL, 0, NULL, NULL, /* No cookies */
9546
                                     uri_in, uri_out,
L
liguang 已提交
9547
                                     dname, dom_xml, flags);
D
Daniel Veillard 已提交
9548

9549 9550 9551 9552
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
9553

D
Daniel Veillard 已提交
9554

9555 9556
/* Perform is the second step, and it runs on the source host. */
static int
9557 9558 9559 9560 9561 9562 9563
qemuDomainMigratePerform(virDomainPtr dom,
                         const char *cookie,
                         int cookielen,
                         const char *uri,
                         unsigned long flags,
                         const char *dname,
                         unsigned long resource)
9564
{
9565
    virQEMUDriverPtr driver = dom->conn->privateData;
9566 9567
    virDomainObjPtr vm;
    int ret = -1;
9568
    const char *dconnuri = NULL;
9569

9570
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
9571

9572
    qemuDriverLock(driver);
9573
    if (virLockManagerPluginUsesState(driver->lockManager)) {
9574 9575 9576
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot use migrate v2 protocol with lock manager %s"),
                       virLockManagerPluginGetName(driver->lockManager));
9577 9578 9579
        goto cleanup;
    }

9580
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
D
Daniel Veillard 已提交
9581
    if (!vm) {
9582 9583
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
9584 9585
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
9586
        goto cleanup;
D
Daniel Veillard 已提交
9587 9588
    }

9589 9590 9591 9592 9593
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

9594 9595 9596 9597 9598 9599
    /* 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
     */
9600
    ret = qemuMigrationPerform(driver, dom->conn, vm,
9601
                               NULL, dconnuri, uri, cookie, cookielen,
9602
                               NULL, NULL, /* No output cookies in v2 */
9603
                               flags, dname, resource, false);
9604

9605
cleanup:
9606
    qemuDriverUnlock(driver);
9607
    return ret;
D
Daniel Veillard 已提交
9608 9609
}

9610

D
Daniel Veillard 已提交
9611 9612
/* Finish is the third and final step, and it runs on the destination host. */
static virDomainPtr
9613 9614 9615 9616 9617 9618 9619
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 已提交
9620
{
9621
    virQEMUDriverPtr driver = dconn->privateData;
9622 9623
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
9624

9625
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
9626

9627
    qemuDriverLock(driver);
9628
    vm = virDomainObjListFindByName(driver->domains, dname);
D
Daniel Veillard 已提交
9629
    if (!vm) {
9630 9631
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), dname);
9632
        goto cleanup;
D
Daniel Veillard 已提交
9633 9634
    }

9635 9636 9637 9638
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
9639
    dom = qemuMigrationFinish(driver, dconn, vm,
9640
                              NULL, 0, NULL, NULL, /* No cookies */
9641
                              flags, retcode, false);
9642

9643
cleanup:
9644
    qemuDriverUnlock(driver);
9645
    return dom;
D
Daniel Veillard 已提交
9646 9647
}

9648

9649 9650 9651 9652 9653 9654
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
9655
                        const char *xmlin,
9656 9657 9658
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
9659
                        const char *dname,
9660 9661
                        unsigned long resource ATTRIBUTE_UNUSED)
{
9662
    virQEMUDriverPtr driver = domain->conn->privateData;
9663 9664
    virDomainObjPtr vm;
    char *xml = NULL;
9665
    enum qemuDomainAsyncJob asyncJob;
9666

9667
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
9668 9669

    qemuDriverLock(driver);
9670
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
9671 9672 9673
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
9674 9675
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
9676 9677 9678
        goto cleanup;
    }

9679 9680 9681
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
            goto cleanup;
9682
        asyncJob = QEMU_ASYNC_JOB_MIGRATION_OUT;
9683
    } else {
W
Wen Congyang 已提交
9684
        if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9685
            goto cleanup;
9686
        asyncJob = QEMU_ASYNC_JOB_NONE;
9687 9688
    }

L
liguang 已提交
9689
    if (!virDomainObjIsActive(vm) && !(flags & VIR_MIGRATE_OFFLINE)) {
9690 9691
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
9692 9693 9694
        goto endjob;
    }

9695 9696 9697
    /* Check if there is any ejected media.
     * We don't want to require them on the destination.
     */
L
liguang 已提交
9698 9699
    if (!(flags & VIR_MIGRATE_OFFLINE) &&
        qemuDomainCheckEjectableMedia(driver, vm, asyncJob) < 0)
9700 9701
        goto endjob;

9702
    if (!(xml = qemuMigrationBegin(driver, vm, xmlin, dname,
9703 9704
                                   cookieout, cookieoutlen,
                                   flags)))
9705 9706 9707 9708 9709 9710 9711
        goto endjob;

    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        /* We keep the job active across API calls until the confirm() call.
         * This prevents any other APIs being invoked while migration is taking
         * place.
         */
9712 9713 9714
        if (qemuDriverCloseCallbackSet(driver, vm, domain->conn,
                                       qemuMigrationCleanup) < 0)
            goto endjob;
9715 9716
        if (qemuMigrationJobContinue(vm) == 0) {
            vm = NULL;
9717 9718
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("domain disappeared"));
9719 9720 9721 9722 9723 9724 9725
            VIR_FREE(xml);
            if (cookieout)
                VIR_FREE(*cookieout);
        }
    } else {
        goto endjob;
    }
9726 9727

cleanup:
9728
    if (vm)
9729
        virObjectUnlock(vm);
9730 9731
    qemuDriverUnlock(driver);
    return xml;
9732 9733 9734 9735 9736 9737 9738 9739 9740 9741

endjob:
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobFinish(driver, vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    }
    goto cleanup;
9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756
}

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)
{
9757
    virQEMUDriverPtr driver = dconn->privateData;
9758 9759
    int ret = -1;

9760
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
9761 9762 9763 9764 9765 9766 9767 9768

    *uri_out = NULL;

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

    if (!dom_xml) {
9775 9776
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no domain XML passed"));
9777 9778 9779 9780 9781 9782 9783
        goto cleanup;
    }

    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     uri_in, uri_out,
L
liguang 已提交
9784
                                     dname, dom_xml, flags);
9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


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

9807
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
9808 9809

    if (!dom_xml) {
9810 9811
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no domain XML passed"));
9812 9813 9814
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
9815 9816
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
9817 9818 9819
        goto cleanup;
    }
    if (st == NULL) {
9820 9821
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("tunnelled migration requested but NULL stream passed"));
9822 9823 9824 9825 9826 9827 9828
        goto cleanup;
    }

    qemuDriverLock(driver);
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
L
liguang 已提交
9829
                                     st, dname, dom_xml, flags);
9830 9831 9832 9833 9834 9835 9836 9837 9838
    qemuDriverUnlock(driver);

cleanup:
    return ret;
}


static int
qemuDomainMigratePerform3(virDomainPtr dom,
9839
                          const char *xmlin,
9840 9841 9842 9843
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
9844
                          const char *dconnuri,
9845 9846 9847 9848 9849
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
9850
    virQEMUDriverPtr driver = dom->conn->privateData;
9851 9852 9853
    virDomainObjPtr vm;
    int ret = -1;

9854
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
9855 9856

    qemuDriverLock(driver);
9857
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
9858 9859 9860
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
9861 9862
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
9863 9864 9865
        goto cleanup;
    }

9866
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
9867
                               dconnuri, uri, cookiein, cookieinlen,
9868
                               cookieout, cookieoutlen,
9869
                               flags, dname, resource, true);
9870 9871 9872 9873 9874 9875 9876

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


9877
static virDomainPtr
9878 9879 9880 9881 9882 9883
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
9884
                         const char *dconnuri ATTRIBUTE_UNUSED,
9885 9886
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
9887
                         int cancelled)
9888
{
9889
    virQEMUDriverPtr driver = dconn->privateData;
9890
    virDomainObjPtr vm;
9891
    virDomainPtr dom = NULL;
9892

9893
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
9894 9895

    qemuDriverLock(driver);
9896
    vm = virDomainObjListFindByName(driver->domains, dname);
9897
    if (!vm) {
9898 9899
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), dname);
9900 9901 9902
        goto cleanup;
    }

9903 9904 9905 9906
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
9907 9908 9909

cleanup:
    qemuDriverUnlock(driver);
9910
    return dom;
9911 9912 9913 9914 9915 9916 9917 9918 9919
}

static int
qemuDomainMigrateConfirm3(virDomainPtr domain,
                          const char *cookiein,
                          int cookieinlen,
                          unsigned long flags,
                          int cancelled)
{
9920
    virQEMUDriverPtr driver = domain->conn->privateData;
9921 9922
    virDomainObjPtr vm;
    int ret = -1;
9923
    enum qemuMigrationJobPhase phase;
9924
    virQEMUDriverConfigPtr cfg = NULL;
9925

9926
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
9927 9928

    qemuDriverLock(driver);
9929
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
9930 9931 9932
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
9933 9934
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
9935 9936 9937
        goto cleanup;
    }

9938 9939
    cfg = virQEMUDriverGetConfig(driver);

9940
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
9941 9942
        goto cleanup;

9943 9944 9945 9946 9947 9948
    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);
9949
    qemuDriverCloseCallbackUnset(driver, vm, qemuMigrationCleanup);
9950

9951 9952
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
9953 9954
                               flags, cancelled);

9955
    if (qemuMigrationJobFinish(driver, vm) == 0) {
9956 9957 9958 9959
        vm = NULL;
    } else if (!virDomainObjIsActive(vm) &&
               (!vm->persistent || (flags & VIR_MIGRATE_UNDEFINE_SOURCE))) {
        if (flags & VIR_MIGRATE_UNDEFINE_SOURCE)
9960
            virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm);
9961
        qemuDomainRemoveInactive(driver, vm);
9962 9963 9964
        vm = NULL;
    }

9965
cleanup:
9966
    if (vm)
9967
        virObjectUnlock(vm);
9968
    qemuDriverUnlock(driver);
9969
    virObjectUnref(cfg);
9970 9971 9972 9973
    return ret;
}


9974
static int
9975 9976 9977 9978 9979
qemuNodeDeviceGetPciInfo(virNodeDevicePtr dev,
                         unsigned *domain,
                         unsigned *bus,
                         unsigned *slot,
                         unsigned *function)
9980 9981 9982 9983 9984 9985 9986 9987 9988 9989
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDevCapsDefPtr cap;
    char *xml = NULL;
    int ret = -1;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto out;

9990
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007
    if (!def)
        goto out;

    cap = def->caps;
    while (cap) {
        if (cap->type == VIR_NODE_DEV_CAP_PCI_DEV) {
            *domain   = cap->data.pci_dev.domain;
            *bus      = cap->data.pci_dev.bus;
            *slot     = cap->data.pci_dev.slot;
            *function = cap->data.pci_dev.function;
            break;
        }

        cap = cap->next;
    }

    if (!cap) {
10008 10009
        virReportError(VIR_ERR_INVALID_ARG,
                       _("device %s is not a PCI device"), dev->name);
10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020
        goto out;
    }

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

static int
10021
qemuNodeDeviceDettach(virNodeDevicePtr dev)
10022
{
10023
    virQEMUDriverPtr driver = dev->conn->privateData;
10024
    virPCIDevicePtr pci;
10025 10026
    unsigned domain, bus, slot, function;
    int ret = -1;
10027
    bool in_inactive_list = false;
10028

10029
    if (qemuNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
10030 10031
        return -1;

10032
    pci = virPCIDeviceNew(domain, bus, slot, function);
10033 10034 10035
    if (!pci)
        return -1;

10036
    qemuDriverLock(driver);
10037
    in_inactive_list = virPCIDeviceListFind(driver->inactivePciHostdevs, pci);
10038

10039 10040
    if (virPCIDeviceDetach(pci, driver->activePciHostdevs,
                           driver->inactivePciHostdevs, "pci-stub") < 0)
10041 10042 10043 10044
        goto out;

    ret = 0;
out:
10045
    qemuDriverUnlock(driver);
10046
    if (in_inactive_list)
10047
        virPCIDeviceFree(pci);
10048 10049 10050 10051
    return ret;
}

static int
10052
qemuNodeDeviceReAttach(virNodeDevicePtr dev)
10053
{
10054
    virQEMUDriverPtr driver = dev->conn->privateData;
10055 10056
    virPCIDevicePtr pci;
    virPCIDevicePtr other;
10057 10058 10059
    unsigned domain, bus, slot, function;
    int ret = -1;

10060
    if (qemuNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
10061 10062
        return -1;

10063
    pci = virPCIDeviceNew(domain, bus, slot, function);
10064 10065 10066
    if (!pci)
        return -1;

10067
    other = virPCIDeviceListFind(driver->activePciHostdevs, pci);
10068
    if (other) {
10069
        const char *other_name = virPCIDeviceGetUsedBy(other);
10070 10071

        if (other_name)
10072 10073
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is still in use by domain %s"),
10074
                           virPCIDeviceGetName(pci), other_name);
10075
        else
10076 10077
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is still in use"),
10078
                           virPCIDeviceGetName(pci));
10079 10080
    }

10081
    virPCIDeviceReattachInit(pci);
10082

10083
    qemuDriverLock(driver);
10084 10085
    if (virPCIDeviceReattach(pci, driver->activePciHostdevs,
                             driver->inactivePciHostdevs, "pci-stub") < 0)
10086 10087 10088 10089
        goto out;

    ret = 0;
out:
10090
    qemuDriverUnlock(driver);
10091
    virPCIDeviceFree(pci);
10092 10093 10094 10095
    return ret;
}

static int
10096
qemuNodeDeviceReset(virNodeDevicePtr dev)
10097
{
10098
    virQEMUDriverPtr driver = dev->conn->privateData;
10099
    virPCIDevicePtr pci;
10100 10101 10102
    unsigned domain, bus, slot, function;
    int ret = -1;

10103
    if (qemuNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
10104 10105
        return -1;

10106
    pci = virPCIDeviceNew(domain, bus, slot, function);
10107 10108 10109
    if (!pci)
        return -1;

10110 10111
    qemuDriverLock(driver);

10112 10113
    if (virPCIDeviceReset(pci, driver->activePciHostdevs,
                          driver->inactivePciHostdevs) < 0)
10114 10115 10116 10117
        goto out;

    ret = 0;
out:
10118
    qemuDriverUnlock(driver);
10119
    virPCIDeviceFree(pci);
10120 10121 10122
    return ret;
}

10123 10124 10125
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
10126
               unsigned int flags)
10127
{
10128
    virQEMUDriverPtr driver = conn->privateData;
10129 10130
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
10131 10132
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

10133 10134
    qemuDriverLock(driver);

10135
    if (!driver->caps) {
10136 10137
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot get host capabilities"));
J
Jiri Denemark 已提交
10138 10139
    } else if (!driver->caps->host.cpu ||
               !driver->caps->host.cpu->model) {
10140 10141
        VIR_WARN("cannot get host CPU capabilities");
        ret = VIR_CPU_COMPARE_INCOMPATIBLE;
E
Eric Blake 已提交
10142
    } else {
10143
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
E
Eric Blake 已提交
10144
    }
10145 10146 10147 10148 10149 10150

    qemuDriverUnlock(driver);

    return ret;
}

10151

10152 10153 10154 10155
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
10156
                unsigned int flags)
10157 10158 10159
{
    char *cpu;

E
Eric Blake 已提交
10160 10161
    virCheckFlags(0, NULL);

10162 10163 10164 10165 10166
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

10167 10168 10169 10170 10171 10172 10173

static int qemuDomainGetJobInfo(virDomainPtr dom,
                                virDomainJobInfoPtr info) {
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

10174
    if (!(vm = qemuDomObjFromDomain(dom)))
10175 10176 10177 10178 10179
        goto cleanup;

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
10180
        if (priv->job.asyncJob && !priv->job.dump_memory_only) {
10181
            memcpy(info, &priv->job.info, sizeof(*info));
10182 10183 10184 10185 10186 10187

            /* 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
             */
10188
            if (virTimeMillisNow(&info->timeElapsed) < 0)
10189
                goto cleanup;
10190
            info->timeElapsed -= priv->job.start;
10191 10192 10193 10194 10195
        } else {
            memset(info, 0, sizeof(*info));
            info->type = VIR_DOMAIN_JOB_NONE;
        }
    } else {
10196 10197
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
10198 10199 10200 10201 10202 10203 10204
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
10205
        virObjectUnlock(vm);
10206 10207 10208 10209
    return ret;
}


10210
static int qemuDomainAbortJob(virDomainPtr dom) {
10211
    virQEMUDriverPtr driver = dom->conn->privateData;
10212 10213 10214 10215
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

10216
    if (!(vm = qemuDomObjFromDomain(dom)))
10217 10218
        goto cleanup;

10219 10220
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
10221

10222
    if (!virDomainObjIsActive(vm)) {
10223 10224
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
10225
        goto endjob;
10226 10227
    }

10228 10229
    priv = vm->privateData;

10230
    if (!priv->job.asyncJob || priv->job.dump_memory_only) {
10231 10232
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("no job is active on the domain"));
10233 10234
        goto endjob;
    } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_IN) {
10235 10236 10237
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot abort incoming migration;"
                         " use virDomainDestroy instead"));
10238 10239 10240 10241
        goto endjob;
    }

    VIR_DEBUG("Cancelling job at client request");
10242
    qemuDomainObjAbortAsyncJob(vm);
10243
    qemuDomainObjEnterMonitor(driver, vm);
10244 10245 10246 10247 10248 10249
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

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

cleanup:
    if (vm)
10253
        virObjectUnlock(vm);
10254 10255 10256 10257
    return ret;
}


10258 10259 10260 10261 10262
static int
qemuDomainMigrateSetMaxDowntime(virDomainPtr dom,
                                unsigned long long downtime,
                                unsigned int flags)
{
10263
    virQEMUDriverPtr driver = dom->conn->privateData;
10264 10265 10266 10267
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

10268
    virCheckFlags(0, -1);
10269

10270 10271
    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
10272

10273 10274 10275
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

10276
    if (!virDomainObjIsActive(vm)) {
10277 10278
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
10279
        goto endjob;
10280 10281 10282 10283
    }

    priv = vm->privateData;

10284
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
10285 10286
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not being migrated"));
10287
        goto endjob;
10288 10289
    }

10290
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
10291
    qemuDomainObjEnterMonitor(driver, vm);
10292 10293 10294 10295 10296 10297
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

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

cleanup:
    if (vm)
10301
        virObjectUnlock(vm);
10302 10303 10304
    return ret;
}

10305 10306 10307 10308 10309
static int
qemuDomainMigrateSetMaxSpeed(virDomainPtr dom,
                             unsigned long bandwidth,
                             unsigned int flags)
{
10310
    virQEMUDriverPtr driver = dom->conn->privateData;
10311 10312 10313 10314 10315 10316
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

10317 10318
    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
10319 10320

    priv = vm->privateData;
10321 10322 10323
    if (virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
            goto cleanup;
10324

10325
        if (!virDomainObjIsActive(vm)) {
10326 10327
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is not running"));
10328 10329 10330
            goto endjob;
        }

10331 10332 10333 10334
        VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
        qemuDomainObjExitMonitor(driver, vm);
10335

10336 10337
        if (ret == 0)
            priv->migMaxBandwidth = bandwidth;
10338

10339
endjob:
10340 10341 10342 10343 10344 10345
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    } else {
        priv->migMaxBandwidth = bandwidth;
        ret = 0;
    }
10346 10347 10348

cleanup:
    if (vm)
10349
        virObjectUnlock(vm);
10350 10351 10352
    return ret;
}

10353 10354 10355 10356 10357 10358
static int
qemuDomainMigrateGetMaxSpeed(virDomainPtr dom,
                             unsigned long *bandwidth,
                             unsigned int flags)
{
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
10359
    qemuDomainObjPrivatePtr priv;
10360 10361 10362 10363
    int ret = -1;

    virCheckFlags(0, -1);

10364
    if (!(vm = qemuDomObjFromDomain(dom)))
10365 10366
        goto cleanup;

J
Jim Fehlig 已提交
10367 10368
    priv = vm->privateData;
    *bandwidth = priv->migMaxBandwidth;
10369 10370 10371 10372
    ret = 0;

cleanup:
    if (vm)
10373
        virObjectUnlock(vm);
10374 10375 10376
    return ret;
}

10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388
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
10389
qemuDomainPrepareDiskChainElement(virQEMUDriverPtr driver,
10390 10391 10392
                                  virDomainObjPtr vm,
                                  virCgroupPtr cgroup,
                                  virDomainDiskDefPtr disk,
10393
                                  const char *file,
10394 10395 10396 10397 10398 10399 10400 10401 10402 10403
                                  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;
10404
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
10405

10406
    disk->src = (char *) file; /* casting away const is safe here */
10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418
    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);
        if (cgroup && qemuTeardownDiskCgroup(vm, cgroup, disk) < 0)
            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);
10419
    } else if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433
                                       vm, disk) < 0 ||
               (cgroup && qemuSetupDiskCgroup(vm, cgroup, disk) < 0) ||
               virSecurityManagerSetImageLabel(driver->securityManager,
                                               vm->def, disk) < 0) {
        goto cleanup;
    }

    ret = 0;

cleanup:
    disk->src = origsrc;
    disk->format = origformat;
    disk->backingChain = origchain;
    disk->readonly = origreadonly;
10434
    virObjectUnref(cfg);
10435 10436 10437 10438
    return ret;
}


C
Chris Lalancette 已提交
10439

10440
/* this function expects the driver lock to be held by the caller */
10441
static int
10442
qemuDomainSnapshotFSFreeze(virQEMUDriverPtr driver,
10443 10444 10445 10446 10447
                           virDomainObjPtr vm) {
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int freezed;

    if (priv->agentError) {
10448
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
10449 10450
                       _("QEMU guest agent is not "
                         "available due to an error"));
10451 10452 10453
        return -1;
    }
    if (!priv->agent) {
10454 10455
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("QEMU guest agent is not configured"));
10456 10457 10458
        return -1;
    }

10459
    qemuDomainObjEnterAgentWithDriver(driver, vm);
10460
    freezed = qemuAgentFSFreeze(priv->agent);
10461
    qemuDomainObjExitAgentWithDriver(driver, vm);
10462 10463 10464 10465 10466

    return freezed;
}

static int
10467
qemuDomainSnapshotFSThaw(virQEMUDriverPtr driver,
E
Eric Blake 已提交
10468 10469
                         virDomainObjPtr vm, bool report)
{
10470 10471
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int thawed;
E
Eric Blake 已提交
10472
    virErrorPtr err = NULL;
10473 10474

    if (priv->agentError) {
E
Eric Blake 已提交
10475
        if (report)
10476
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
10477 10478
                           _("QEMU guest agent is not "
                             "available due to an error"));
10479 10480 10481
        return -1;
    }
    if (!priv->agent) {
E
Eric Blake 已提交
10482
        if (report)
10483 10484
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
10485 10486 10487 10488
        return -1;
    }

    qemuDomainObjEnterAgent(driver, vm);
E
Eric Blake 已提交
10489
    if (!report)
10490
        err = virSaveLastError();
10491
    thawed = qemuAgentFSThaw(priv->agent);
10492 10493
    if (!report)
        virSetError(err);
10494 10495
    qemuDomainObjExitAgent(driver, vm);

10496
    virFreeError(err);
10497 10498 10499
    return thawed;
}

10500 10501
/* The domain is expected to be locked and inactive. */
static int
10502
qemuDomainSnapshotCreateInactiveInternal(virQEMUDriverPtr driver,
10503 10504
                                         virDomainObjPtr vm,
                                         virDomainSnapshotObjPtr snap)
10505
{
E
Eric Blake 已提交
10506
    return qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-c", false);
10507 10508
}

10509 10510
/* The domain is expected to be locked and inactive. */
static int
10511
qemuDomainSnapshotCreateInactiveExternal(virQEMUDriverPtr driver,
10512 10513 10514 10515 10516 10517 10518 10519 10520
                                         virDomainObjPtr vm,
                                         virDomainSnapshotObjPtr snap,
                                         bool reuse)
{
    int i;
    virDomainSnapshotDiskDefPtr snapdisk;
    virDomainDiskDefPtr defdisk;
    virCommandPtr cmd = NULL;
    const char *qemuImgPath;
10521 10522
    virBitmapPtr created = NULL;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
10523 10524 10525
    int ret = -1;

    if (!(qemuImgPath = qemuFindQemuImgBinary(driver)))
10526
        goto cleanup;
10527 10528 10529

    if (!(created = virBitmapNew(snap->def->ndisks))) {
        virReportOOMError();
10530
        goto cleanup;
10531 10532 10533 10534 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
    }

    /* 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 {
10560
            if (!cfg->allowDiskFormatProbing) {
10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607
                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);
            if (!(defdisk->src = strdup(snapdisk->file))) {
                /* we cannot rollback here in a sane way */
                virReportOOMError();
                goto cleanup;
            }
            defdisk->format = snapdisk->format;
        }
    }

    ret = 0;

cleanup:
    virCommandFree(cmd);

    /* unlink images if creation has failed */
10608
    if (ret < 0 && created) {
10609 10610 10611 10612 10613 10614 10615 10616 10617
        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);
10618
    virObjectUnref(cfg);
10619 10620 10621 10622

    return ret;
}

10623

10624 10625
/* The domain is expected to be locked and active. */
static int
10626
qemuDomainSnapshotCreateActiveInternal(virConnectPtr conn,
10627
                                       virQEMUDriverPtr driver,
10628 10629 10630
                                       virDomainObjPtr *vmptr,
                                       virDomainSnapshotObjPtr snap,
                                       unsigned int flags)
10631 10632 10633
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
10634
    virDomainEventPtr event = NULL;
10635 10636
    bool resume = false;
    int ret = -1;
10637

10638
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
10639 10640
        return -1;

10641
    if (!virDomainObjIsActive(vm)) {
10642 10643
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
10644 10645 10646
        goto endjob;
    }

J
Jiri Denemark 已提交
10647
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
10648 10649 10650 10651
        /* 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.
         */
10652 10653
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
10654 10655 10656 10657
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
10658 10659
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit"));
10660 10661 10662 10663
            goto cleanup;
        }
    }

10664
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
10665 10666
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
10667 10668 10669 10670 10671 10672
    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);
10673
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
10674 10675 10676 10677 10678 10679 10680
        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;
    }
10681

10682 10683
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
10684
        qemuProcessStartCPUs(driver, vm, conn,
10685
                             VIR_DOMAIN_RUNNING_UNPAUSED,
10686 10687 10688 10689 10690 10691 10692 10693
                             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"));
        }
10694 10695
    }

10696
endjob:
10697
    if (vm && qemuDomainObjEndJob(driver, vm) == 0) {
10698 10699
        /* Only possible if a transient vm quit while our locks were down,
         * in which case we don't want to save snapshot metadata.  */
10700
        *vmptr = NULL;
10701 10702
        ret = -1;
    }
10703

10704 10705 10706
    if (event)
        qemuDomainEventQueue(driver, event);

10707 10708 10709
    return ret;
}

10710
static int
E
Eric Blake 已提交
10711 10712
qemuDomainSnapshotPrepare(virDomainObjPtr vm, virDomainSnapshotDefPtr def,
                          unsigned int *flags)
10713 10714 10715 10716 10717
{
    int ret = -1;
    int i;
    bool active = virDomainObjIsActive(vm);
    struct stat st;
10718
    bool reuse = (*flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) != 0;
10719
    bool atomic = (*flags & VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC) != 0;
10720
    bool found_internal = false;
10721 10722
    int external = 0;
    qemuDomainObjPrivatePtr priv = vm->privateData;
10723

E
Eric Blake 已提交
10724 10725
    if (def->state == VIR_DOMAIN_DISK_SNAPSHOT &&
        reuse && !qemuCapsGet(priv->caps, QEMU_CAPS_TRANSACTION)) {
10726 10727
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("reuse is not supported with this QEMU binary"));
10728 10729 10730
        goto cleanup;
    }

10731 10732
    for (i = 0; i < def->ndisks; i++) {
        virDomainSnapshotDiskDefPtr disk = &def->disks[i];
E
Eric Blake 已提交
10733
        virDomainDiskDefPtr dom_disk = vm->def->disks[i];
10734 10735

        switch (disk->snapshot) {
E
Eric Blake 已提交
10736
        case VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL:
E
Eric Blake 已提交
10737 10738 10739 10740 10741
            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;
10742
            }
10743 10744
            if (vm->def->disks[i]->format > 0 &&
                vm->def->disks[i]->format != VIR_STORAGE_FILE_QCOW2) {
10745 10746 10747 10748
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("internal snapshot for disk %s unsupported "
                                 "for storage type %s"),
                               disk->name,
10749 10750
                               virStorageFileFormatTypeToString(
                                   vm->def->disks[i]->format));
10751 10752
                goto cleanup;
            }
E
Eric Blake 已提交
10753 10754 10755 10756 10757 10758 10759
            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;
            }
10760
            found_internal = true;
10761 10762
            break;

E
Eric Blake 已提交
10763
        case VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL:
10764 10765 10766 10767
            if (!disk->format) {
                disk->format = VIR_STORAGE_FILE_QCOW2;
            } else if (disk->format != VIR_STORAGE_FILE_QCOW2 &&
                       disk->format != VIR_STORAGE_FILE_QED) {
10768 10769 10770
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("external snapshot format for disk %s "
                                 "is unsupported: %s"),
10771 10772
                               disk->name,
                               virStorageFileFormatTypeToString(disk->format));
10773 10774 10775 10776 10777 10778 10779 10780
                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;
10781 10782 10783 10784 10785
                } else if (reuse) {
                    virReportSystemError(errno,
                                         _("missing existing file for disk %s: %s"),
                                         disk->name, disk->file);
                    goto cleanup;
10786
                }
10787
            } else if (!S_ISBLK(st.st_mode) && st.st_size && !reuse) {
10788 10789 10790 10791
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("external snapshot file for disk %s already "
                                 "exists and is not a block device: %s"),
                               disk->name, disk->file);
10792 10793
                goto cleanup;
            }
10794
            external++;
10795 10796
            break;

E
Eric Blake 已提交
10797
        case VIR_DOMAIN_SNAPSHOT_LOCATION_NONE:
10798 10799
            break;

E
Eric Blake 已提交
10800
        case VIR_DOMAIN_SNAPSHOT_LOCATION_DEFAULT:
10801
        default:
10802 10803
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unexpected code path"));
10804 10805 10806 10807
            goto cleanup;
        }
    }

10808 10809 10810
    /* internal snapshot requires a disk image to store the memory image to */
    if (def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL &&
        !found_internal) {
10811
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10812
                       _("internal checkpoints require at least "
10813
                         "one disk to be selected for snapshot"));
10814 10815
        goto cleanup;
    }
10816

10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838
    /* 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 已提交
10839
    if (def->state != VIR_DOMAIN_DISK_SNAPSHOT && active) {
10840
        if (external == 1 ||
10841
            qemuCapsGet(priv->caps, QEMU_CAPS_TRANSACTION)) {
10842 10843
            *flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
        } else if (atomic && external > 1) {
10844 10845 10846
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("atomic live snapshot of multiple disks "
                             "is unsupported"));
10847 10848 10849
            goto cleanup;
        }
    }
10850 10851 10852 10853 10854 10855 10856 10857 10858

    ret = 0;

cleanup:
    return ret;
}

/* The domain is expected to hold monitor lock.  */
static int
10859
qemuDomainSnapshotCreateSingleDiskActive(virQEMUDriverPtr driver,
10860
                                         virDomainObjPtr vm,
10861
                                         virCgroupPtr cgroup,
10862
                                         virDomainSnapshotDiskDefPtr snap,
10863
                                         virDomainDiskDefPtr disk,
10864
                                         virDomainDiskDefPtr persistDisk,
10865 10866
                                         virJSONValuePtr actions,
                                         bool reuse)
10867 10868 10869 10870
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *device = NULL;
    char *source = NULL;
10871 10872
    int format = snap->format;
    const char *formatStr = NULL;
10873
    char *persistSource = NULL;
10874
    int ret = -1;
10875 10876
    int fd = -1;
    bool need_unlink = false;
10877

E
Eric Blake 已提交
10878
    if (snap->snapshot != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
10879 10880
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected code path"));
10881 10882 10883 10884 10885
        return -1;
    }

    if (virAsprintf(&device, "drive-%s", disk->info.alias) < 0 ||
        !(source = strdup(snap->file)) ||
10886
        (persistDisk &&
10887
         !(persistSource = strdup(source)))) {
10888 10889 10890 10891
        virReportOOMError();
        goto cleanup;
    }

10892 10893
    /* create the stub file and set selinux labels; manipulate disk in
     * place, in a way that can be reverted on failure. */
10894 10895 10896 10897 10898 10899 10900
    if (!reuse) {
        fd = qemuOpenFile(driver, source, O_WRONLY | O_TRUNC | O_CREAT,
                          &need_unlink, NULL);
        if (fd < 0)
            goto cleanup;
        VIR_FORCE_CLOSE(fd);
    }
10901

10902 10903 10904 10905 10906 10907 10908 10909
    /* 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;
10910

10911 10912 10913 10914
    if (qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, source,
                                          VIR_DISK_CHAIN_READ_WRITE) < 0) {
        qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, source,
                                          VIR_DISK_CHAIN_NO_ACCESS);
10915 10916 10917 10918
        goto cleanup;
    }

    /* create the actual snapshot */
10919 10920
    if (snap->format)
        formatStr = virStorageFileFormatTypeToString(snap->format);
10921
    ret = qemuMonitorDiskSnapshot(priv->mon, actions, device, source,
10922
                                  formatStr, reuse);
10923 10924 10925 10926 10927
    virDomainAuditDisk(vm, disk->src, source, "snapshot", ret >= 0);
    if (ret < 0)
        goto cleanup;

    /* Update vm in place to match changes.  */
10928
    need_unlink = false;
10929 10930 10931
    VIR_FREE(disk->src);
    disk->src = source;
    source = NULL;
10932
    disk->format = format;
10933 10934 10935 10936
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
10937
        persistDisk->format = format;
10938
    }
10939 10940

cleanup:
10941 10942
    if (need_unlink && unlink(source))
        VIR_WARN("unable to unlink just-created %s", source);
10943 10944
    VIR_FREE(device);
    VIR_FREE(source);
10945
    VIR_FREE(persistSource);
10946 10947 10948
    return ret;
}

10949 10950 10951 10952
/* The domain is expected to hold monitor lock.  This is the
 * counterpart to qemuDomainSnapshotCreateSingleDiskActive, called
 * only on a failed transaction. */
static void
10953
qemuDomainSnapshotUndoSingleDiskActive(virQEMUDriverPtr driver,
10954
                                       virDomainObjPtr vm,
10955
                                       virCgroupPtr cgroup,
10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966
                                       virDomainDiskDefPtr origdisk,
                                       virDomainDiskDefPtr disk,
                                       virDomainDiskDefPtr persistDisk,
                                       bool need_unlink)
{
    char *source = NULL;
    char *persistSource = NULL;
    struct stat st;

    if (!(source = strdup(origdisk->src)) ||
        (persistDisk &&
10967
         !(persistSource = strdup(source)))) {
10968 10969 10970 10971
        virReportOOMError();
        goto cleanup;
    }

10972 10973
    qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, origdisk->src,
                                      VIR_DISK_CHAIN_NO_ACCESS);
10974
    if (need_unlink && stat(disk->src, &st) == 0 &&
10975
        S_ISREG(st.st_mode) && unlink(disk->src) < 0)
10976 10977 10978 10979 10980 10981
        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;
10982
    disk->format = origdisk->format;
10983 10984 10985 10986
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
10987
        persistDisk->format = origdisk->format;
10988 10989 10990 10991 10992 10993 10994
    }

cleanup:
    VIR_FREE(source);
    VIR_FREE(persistSource);
}

10995 10996
/* The domain is expected to be locked and active. */
static int
10997
qemuDomainSnapshotCreateDiskActive(virQEMUDriverPtr driver,
10998
                                   virDomainObjPtr vm,
10999
                                   virDomainSnapshotObjPtr snap,
11000 11001
                                   unsigned int flags,
                                   enum qemuDomainAsyncJob asyncJob)
11002
{
11003 11004
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virJSONValuePtr actions = NULL;
11005 11006
    int ret = -1;
    int i;
11007
    bool persist = false;
11008
    bool reuse = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) != 0;
11009
    virCgroupPtr cgroup = NULL;
11010
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
11011

11012
    if (!virDomainObjIsActive(vm)) {
11013 11014
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
11015
        goto cleanup;
11016 11017
    }

11018 11019
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES) &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0)) {
11020 11021 11022
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to find cgroup for %s"),
                       vm->def->name);
11023
        goto cleanup;
11024 11025 11026
    }
    /* 'cgroup' is still NULL if cgroups are disabled.  */

11027
    if (qemuCapsGet(priv->caps, QEMU_CAPS_TRANSACTION)) {
11028
        if (!(actions = virJSONValueNewArray())) {
11029 11030 11031
            virReportOOMError();
            goto cleanup;
        }
11032 11033 11034 11035 11036
    } else if (!qemuCapsGet(priv->caps, QEMU_CAPS_DISK_SNAPSHOT)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("live disk snapshot not supported with this "
                         "QEMU binary"));
        goto cleanup;
11037
    }
11038 11039

    /* No way to roll back if first disk succeeds but later disks
11040
     * fail, unless we have transaction support.
E
Eric Blake 已提交
11041
     * Based on earlier qemuDomainSnapshotPrepare, all
11042 11043
     * disks in this list are now either SNAPSHOT_NO, or
     * SNAPSHOT_EXTERNAL with a valid file name and qcow2 format.  */
11044 11045 11046
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        goto cleanup;

11047
    for (i = 0; i < snap->def->ndisks; i++) {
11048 11049
        virDomainDiskDefPtr persistDisk = NULL;

E
Eric Blake 已提交
11050
        if (snap->def->disks[i].snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE)
11051
            continue;
11052 11053 11054 11055 11056 11057 11058 11059 11060
        if (vm->newDef) {
            int indx = virDomainDiskIndexByName(vm->newDef,
                                                vm->def->disks[i]->dst,
                                                false);
            if (indx >= 0) {
                persistDisk = vm->newDef->disks[indx];
                persist = true;
            }
        }
11061

11062
        ret = qemuDomainSnapshotCreateSingleDiskActive(driver, vm, cgroup,
11063
                                                       &snap->def->disks[i],
11064
                                                       vm->def->disks[i],
11065 11066
                                                       persistDisk, actions,
                                                       reuse);
11067 11068 11069
        if (ret < 0)
            break;
    }
11070 11071 11072
    if (actions) {
        if (ret == 0)
            ret = qemuMonitorTransaction(priv->mon, actions);
E
Eric Blake 已提交
11073
        virJSONValueFree(actions);
11074 11075 11076 11077 11078 11079
        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 已提交
11080 11081
                if (snap->def->disks[i].snapshot ==
                    VIR_DOMAIN_SNAPSHOT_LOCATION_NONE)
11082 11083 11084 11085 11086 11087 11088 11089 11090
                    continue;
                if (vm->newDef) {
                    int indx = virDomainDiskIndexByName(vm->newDef,
                                                        vm->def->disks[i]->dst,
                                                        false);
                    if (indx >= 0)
                        persistDisk = vm->newDef->disks[indx];
                }

11091
                qemuDomainSnapshotUndoSingleDiskActive(driver, vm, cgroup,
11092 11093 11094 11095 11096 11097 11098
                                                       snap->def->dom->disks[i],
                                                       vm->def->disks[i],
                                                       persistDisk,
                                                       need_unlink);
            }
        }
    }
11099
    qemuDomainObjExitMonitorWithDriver(driver, vm);
11100 11101 11102 11103 11104

cleanup:
    virCgroupFree(&cgroup);

    if (ret == 0 || !qemuCapsGet(priv->caps, QEMU_CAPS_TRANSACTION)) {
11105 11106
        if (virDomainSaveStatus(driver->caps, cfg->stateDir, vm) < 0 ||
            (persist && virDomainSaveConfig(cfg->configDir, vm->newDef) < 0))
11107 11108
            ret = -1;
    }
11109
    virObjectUnref(cfg);
11110 11111 11112 11113 11114 11115 11116

    return ret;
}


static int
qemuDomainSnapshotCreateActiveExternal(virConnectPtr conn,
11117
                                       virQEMUDriverPtr driver,
11118 11119 11120 11121 11122 11123 11124 11125 11126 11127
                                       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;
11128
    bool memory_unlink = false;
11129 11130 11131
    bool atomic = !!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC);
    bool transaction = qemuCapsGet(priv->caps, QEMU_CAPS_TRANSACTION);
    int thaw = 0; /* 1 if freeze succeeded, -1 if freeze failed */
11132
    bool pmsuspended = false;
11133 11134 11135

    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SNAPSHOT) < 0)
11136 11137
        goto cleanup;

11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151
    /* 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) {
        if (qemuDomainSnapshotFSFreeze(driver, vm) < 0) {
            /* helper reported the error */
            thaw = -1;
            goto endjob;
        } else {
            thaw = 1;
        }
    }

11152 11153 11154 11155 11156
    /* 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) {
11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185
        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) {
11186 11187 11188 11189
        /* check if migration is possible */
        if (!qemuMigrationIsAllowed(driver, vm, vm->def, false))
            goto endjob;

11190 11191 11192 11193 11194 11195 11196 11197 11198
        /* 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,
11199
                                        xml, QEMU_SAVE_FORMAT_RAW,
11200 11201 11202 11203
                                        resume, 0,
                                        QEMU_ASYNC_JOB_SNAPSHOT)) < 0)
            goto endjob;

11204 11205 11206
        /* the memory image was created, remove it on errors */
        memory_unlink = true;

11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222
        /* 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 */
11223 11224 11225 11226 11227
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT) {
        virDomainEventPtr event;

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
11228
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
11229 11230 11231
        virDomainAuditStop(vm, "from-snapshot");
        /* We already filtered the _HALT flag for persistent domains
         * only, so this end job never drops the last reference.  */
11232
        ignore_value(qemuDomainObjEndAsyncJob(driver, vm));
11233
        resume = false;
E
Eric Blake 已提交
11234
        thaw = 0;
11235 11236 11237
        vm = NULL;
        if (event)
            qemuDomainEventQueue(driver, event);
11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249
    } 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);
11250 11251
    }

11252
    ret = 0;
11253 11254

endjob:
11255 11256 11257
    if (resume && vm && virDomainObjIsActive(vm) &&
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED,
11258
                             QEMU_ASYNC_JOB_SNAPSHOT) < 0) {
11259 11260 11261 11262 11263 11264 11265 11266 11267 11268
        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"));
        }
11269

11270 11271
        ret = -1;
        goto cleanup;
11272
    }
E
Eric Blake 已提交
11273 11274 11275 11276 11277 11278
    if (vm && thaw != 0 &&
        qemuDomainSnapshotFSThaw(driver, vm, thaw > 0) < 0) {
        /* helper reported the error, if it was needed */
        if (thaw > 0)
            ret = -1;
    }
11279
    if (vm && !qemuDomainObjEndAsyncJob(driver, vm)) {
11280
        /* Only possible if a transient vm quit while our locks were down,
11281 11282
         * in which case we don't want to save snapshot metadata.
         */
11283 11284
        *vmptr = NULL;
        ret = -1;
11285 11286
    }

11287 11288
cleanup:
    VIR_FREE(xml);
11289 11290
    if (memory_unlink && ret < 0)
        unlink(snap->def->file);
11291

11292 11293 11294
    return ret;
}

11295

11296 11297 11298 11299
static virDomainSnapshotPtr
qemuDomainSnapshotCreateXML(virDomainPtr domain,
                            const char *xmlDesc,
                            unsigned int flags)
C
Chris Lalancette 已提交
11300
{
11301
    virQEMUDriverPtr driver = domain->conn->privateData;
C
Chris Lalancette 已提交
11302
    virDomainObjPtr vm = NULL;
11303
    char *xml = NULL;
C
Chris Lalancette 已提交
11304 11305 11306
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
11307
    virDomainSnapshotDefPtr def = NULL;
11308
    bool update_current = true;
11309
    unsigned int parse_flags = VIR_DOMAIN_SNAPSHOT_PARSE_DISKS;
11310
    virDomainSnapshotObjPtr other = NULL;
11311 11312
    int align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL;
    int align_match = true;
11313
    virQEMUDriverConfigPtr cfg = NULL;
C
Chris Lalancette 已提交
11314

11315 11316
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT |
11317
                  VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
11318
                  VIR_DOMAIN_SNAPSHOT_CREATE_HALT |
11319
                  VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
11320
                  VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT |
11321
                  VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE |
11322 11323
                  VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC |
                  VIR_DOMAIN_SNAPSHOT_CREATE_LIVE, NULL);
11324 11325 11326

    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) &&
        !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY)) {
11327 11328
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("quiesce requires disk-only"));
11329 11330
        return NULL;
    }
11331 11332 11333 11334 11335 11336 11337

    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;
11338

C
Chris Lalancette 已提交
11339 11340
    qemuDriverLock(driver);
    virUUIDFormat(domain->uuid, uuidstr);
11341
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
C
Chris Lalancette 已提交
11342
    if (!vm) {
11343 11344
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
C
Chris Lalancette 已提交
11345 11346 11347
        goto cleanup;
    }

11348 11349
    cfg = virQEMUDriverGetConfig(driver);

11350
    if (qemuProcessAutoDestroyActive(driver, vm)) {
11351 11352
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is marked for auto destroy"));
11353 11354
        goto cleanup;
    }
E
Eric Blake 已提交
11355 11356 11357 11358 11359 11360
    if (virDomainHasDiskMirror(vm)) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE, "%s",
                       _("domain has active block copy job"));
        goto cleanup;
    }

11361
    if (!vm->persistent && (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
11362 11363
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot halt after transient domain snapshot"));
11364 11365
        goto cleanup;
    }
11366 11367 11368
    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) ||
        !virDomainObjIsActive(vm))
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_OFFLINE;
11369

11370 11371 11372
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, driver->caps,
                                                QEMU_EXPECTED_VIRT_TYPES,
                                                parse_flags)))
C
Chris Lalancette 已提交
11373 11374
        goto cleanup;

11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392
    /* 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;
        }
11393 11394
    }

11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413
    /* 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;
    }
    if ((def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL ||
         def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL) &&
        flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("disk-only snapshot creation is not compatible with "
                         "memory snapshot"));
        goto cleanup;
    }

11414 11415 11416 11417
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* Prevent circular chains */
        if (def->parent) {
            if (STREQ(def->name, def->parent)) {
11418 11419 11420
                virReportError(VIR_ERR_INVALID_ARG,
                               _("cannot set snapshot %s as its own parent"),
                               def->name);
11421 11422
                goto cleanup;
            }
11423
            other = virDomainSnapshotFindByName(vm->snapshots, def->parent);
11424
            if (!other) {
11425 11426 11427
                virReportError(VIR_ERR_INVALID_ARG,
                               _("parent %s for snapshot %s not found"),
                               def->parent, def->name);
11428 11429 11430 11431
                goto cleanup;
            }
            while (other->def->parent) {
                if (STREQ(other->def->parent, def->name)) {
11432 11433 11434
                    virReportError(VIR_ERR_INVALID_ARG,
                                   _("parent %s would create cycle to %s"),
                                   other->def->name, def->name);
11435 11436
                    goto cleanup;
                }
11437
                other = virDomainSnapshotFindByName(vm->snapshots,
11438 11439 11440 11441 11442 11443 11444 11445 11446 11447
                                                    other->def->parent);
                if (!other) {
                    VIR_WARN("snapshots are inconsistent for %s",
                             vm->def->name);
                    break;
                }
            }
        }

        /* Check that any replacement is compatible */
11448 11449 11450 11451 11452 11453 11454 11455 11456
        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;

        }
11457

11458 11459
        if (def->dom &&
            memcmp(def->dom->uuid, domain->uuid, VIR_UUID_BUFLEN)) {
11460 11461 11462
            virReportError(VIR_ERR_INVALID_ARG,
                           _("definition for snapshot %s must use uuid %s"),
                           def->name, uuidstr);
11463 11464
            goto cleanup;
        }
11465

11466
        other = virDomainSnapshotFindByName(vm->snapshots, def->name);
11467 11468 11469 11470 11471
        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)) {
11472 11473 11474 11475
                virReportError(VIR_ERR_INVALID_ARG,
                               _("cannot change between online and offline "
                                 "snapshot state in snapshot %s"),
                               def->name);
11476 11477
                goto cleanup;
            }
11478

11479 11480
            if ((other->def->state == VIR_DOMAIN_DISK_SNAPSHOT) !=
                (def->state == VIR_DOMAIN_DISK_SNAPSHOT)) {
11481 11482 11483 11484
                virReportError(VIR_ERR_INVALID_ARG,
                               _("cannot change between disk snapshot and "
                                 "system checkpoint in snapshot %s"),
                               def->name);
11485 11486
                goto cleanup;
            }
11487

11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498
            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;
                }
            }
11499

11500 11501
            if (def->dom) {
                if (def->state == VIR_DOMAIN_DISK_SNAPSHOT ||
11502
                    virDomainSnapshotDefIsExternal(def)) {
11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517
                    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;
                }
            }

11518 11519 11520 11521
            if (other == vm->current_snapshot) {
                update_current = true;
                vm->current_snapshot = NULL;
            }
11522

11523 11524
            /* Drop and rebuild the parent relationship, but keep all
             * child relations by reusing snap.  */
11525
            virDomainSnapshotDropParent(other);
11526
            virDomainSnapshotDefFree(other->def);
11527 11528
            other->def = def;
            def = NULL;
11529
            snap = other;
11530 11531 11532 11533 11534 11535 11536 11537 11538 11539
        } 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;
11540
            }
11541
        }
11542 11543 11544
    } else {
        /* Easiest way to clone inactive portion of vm->def is via
         * conversion in and back out of xml.  */
11545
        if (!(xml = qemuDomainDefFormatLive(driver, vm->def, true, true)) ||
11546 11547 11548 11549 11550
            !(def->dom = virDomainDefParseString(driver->caps, xml,
                                                 QEMU_EXPECTED_VIRT_TYPES,
                                                 VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

11551
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
11552 11553
            align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
            align_match = false;
11554 11555 11556 11557
            if (virDomainObjIsActive(vm))
                def->state = VIR_DOMAIN_DISK_SNAPSHOT;
            else
                def->state = VIR_DOMAIN_SHUTOFF;
11558
            def->memory = VIR_DOMAIN_SNAPSHOT_LOCATION_NONE;
11559 11560 11561 11562
        } else if (def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
            def->state = virDomainObjGetState(vm, NULL);
            align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
            align_match = false;
11563 11564
        } else {
            def->state = virDomainObjGetState(vm, NULL);
11565 11566 11567
            def->memory = (def->state == VIR_DOMAIN_SHUTOFF ?
                           VIR_DOMAIN_SNAPSHOT_LOCATION_NONE :
                           VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL);
11568
        }
E
Eric Blake 已提交
11569 11570 11571 11572
        if (virDomainSnapshotAlignDisks(def, align_location,
                                        align_match) < 0 ||
            qemuDomainSnapshotPrepare(vm, def, &flags) < 0)
            goto cleanup;
11573 11574
    }

11575 11576 11577 11578 11579 11580
    if (!snap) {
        if (!(snap = virDomainSnapshotAssignDef(vm->snapshots, def)))
            goto cleanup;

        def = NULL;
    }
C
Chris Lalancette 已提交
11581

11582 11583
    if (update_current)
        snap->def->current = true;
11584
    if (vm->current_snapshot) {
11585 11586 11587 11588 11589 11590
        if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) {
            snap->def->parent = strdup(vm->current_snapshot->def->name);
            if (snap->def->parent == NULL) {
                virReportOOMError();
                goto cleanup;
            }
11591
        }
11592
        if (update_current) {
11593 11594
            vm->current_snapshot->def->current = false;
            if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
11595
                                                cfg->snapshotDir) < 0)
11596 11597 11598
                goto cleanup;
            vm->current_snapshot = NULL;
        }
11599
    }
11600

C
Chris Lalancette 已提交
11601
    /* actually do the snapshot */
11602 11603
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* XXX Should we validate that the redefined snapshot even
11604 11605
         * makes sense, such as checking that qemu-img recognizes the
         * snapshot name in at least one of the domain's disks?  */
11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618
    } 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 已提交
11619
    } else {
11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632
        /* 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 已提交
11633 11634
    }

11635
    /* If we fail after this point, there's not a whole lot we can
C
Chris Lalancette 已提交
11636 11637 11638 11639 11640 11641
     * 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:
11642
    if (vm) {
11643
        if (snapshot && !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
11644
            if (qemuDomainSnapshotWriteMetadata(vm, snap,
11645
                                                cfg->snapshotDir) < 0) {
11646 11647 11648 11649 11650 11651 11652 11653
                /* 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);
11654 11655 11656
            } else {
                if (update_current)
                    vm->current_snapshot = snap;
11657
                other = virDomainSnapshotFindByName(vm->snapshots,
11658 11659 11660 11661 11662
                                                    snap->def->parent);
                snap->parent = other;
                other->nchildren++;
                snap->sibling = other->first_child;
                other->first_child = snap;
11663
            }
11664
        } else if (snap) {
11665
            virDomainSnapshotObjListRemove(vm->snapshots, snap);
11666
        }
11667
        virObjectUnlock(vm);
11668 11669
    }
    virDomainSnapshotDefFree(def);
11670
    VIR_FREE(xml);
C
Chris Lalancette 已提交
11671
    qemuDriverUnlock(driver);
11672
    virObjectUnref(cfg);
C
Chris Lalancette 已提交
11673 11674 11675 11676 11677
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
11678
                                       unsigned int flags)
C
Chris Lalancette 已提交
11679 11680 11681 11682
{
    virDomainObjPtr vm = NULL;
    int n = -1;

11683
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
11684
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
11685

11686
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
11687 11688
        goto cleanup;

11689
    n = virDomainSnapshotObjListGetNames(vm->snapshots, NULL, names, nameslen,
11690
                                         flags);
C
Chris Lalancette 已提交
11691 11692 11693

cleanup:
    if (vm)
11694
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
11695 11696 11697 11698
    return n;
}

static int qemuDomainSnapshotNum(virDomainPtr domain,
11699
                                 unsigned int flags)
C
Chris Lalancette 已提交
11700 11701 11702 11703
{
    virDomainObjPtr vm = NULL;
    int n = -1;

11704
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
11705
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
11706

11707
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
11708 11709
        goto cleanup;

11710
    n = virDomainSnapshotObjListNum(vm->snapshots, NULL, flags);
C
Chris Lalancette 已提交
11711 11712 11713

cleanup:
    if (vm)
11714
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
11715 11716 11717
    return n;
}

11718 11719 11720 11721 11722 11723 11724 11725 11726 11727
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);

11728
    if (!(vm = qemuDomObjFromDomain(domain)))
11729 11730
        goto cleanup;

11731
    n = virDomainListSnapshots(vm->snapshots, NULL, domain, snaps, flags);
11732 11733 11734

cleanup:
    if (vm)
11735
        virObjectUnlock(vm);
11736 11737 11738
    return n;
}

11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749
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 |
11750
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
11751

11752
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
11753 11754
        goto cleanup;

11755
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
11756 11757
        goto cleanup;

11758
    n = virDomainSnapshotObjListGetNames(vm->snapshots, snap, names, nameslen,
11759
                                         flags);
11760 11761 11762

cleanup:
    if (vm)
11763
        virObjectUnlock(vm);
11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775
    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 |
11776
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
11777

11778
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
11779 11780
        goto cleanup;

11781
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
11782 11783
        goto cleanup;

11784
    n = virDomainSnapshotObjListNum(vm->snapshots, snap, flags);
11785 11786 11787

cleanup:
    if (vm)
11788
        virObjectUnlock(vm);
11789 11790 11791
    return n;
}

11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803
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);

11804
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
11805 11806
        goto cleanup;

11807
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
11808 11809
        goto cleanup;

11810
    n = virDomainListSnapshots(vm->snapshots, snap, snapshot->domain, snaps,
11811 11812 11813 11814
                               flags);

cleanup:
    if (vm)
11815
        virObjectUnlock(vm);
11816 11817 11818
    return n;
}

C
Chris Lalancette 已提交
11819 11820
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
11821
                                                           unsigned int flags)
C
Chris Lalancette 已提交
11822 11823 11824 11825 11826
{
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

11827 11828
    virCheckFlags(0, NULL);

11829
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
11830 11831
        goto cleanup;

11832
    if (!(snap = qemuSnapObjFromName(vm, name)))
C
Chris Lalancette 已提交
11833 11834 11835 11836 11837 11838
        goto cleanup;

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
    if (vm)
11839
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
11840 11841 11842 11843
    return snapshot;
}

static int qemuDomainHasCurrentSnapshot(virDomainPtr domain,
11844
                                        unsigned int flags)
C
Chris Lalancette 已提交
11845 11846 11847 11848
{
    virDomainObjPtr vm;
    int ret = -1;

11849 11850
    virCheckFlags(0, -1);

11851
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
11852 11853 11854 11855 11856 11857
        goto cleanup;

    ret = (vm->current_snapshot != NULL);

cleanup:
    if (vm)
11858
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
11859 11860 11861
    return ret;
}

11862 11863 11864 11865 11866 11867 11868 11869 11870 11871
static virDomainSnapshotPtr
qemuDomainSnapshotGetParent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

11872
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
11873 11874
        goto cleanup;

11875
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
11876 11877 11878
        goto cleanup;

    if (!snap->def->parent) {
11879 11880 11881
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snap->def->name);
11882 11883 11884 11885 11886 11887 11888
        goto cleanup;
    }

    parent = virGetDomainSnapshot(snapshot->domain, snap->def->parent);

cleanup:
    if (vm)
11889
        virObjectUnlock(vm);
11890 11891 11892
    return parent;
}

C
Chris Lalancette 已提交
11893
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
11894
                                                      unsigned int flags)
C
Chris Lalancette 已提交
11895 11896 11897 11898
{
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

11899 11900
    virCheckFlags(0, NULL);

11901
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
11902 11903 11904
        goto cleanup;

    if (!vm->current_snapshot) {
11905 11906
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                       _("the domain does not have a current snapshot"));
C
Chris Lalancette 已提交
11907 11908 11909 11910 11911 11912 11913
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, vm->current_snapshot->def->name);

cleanup:
    if (vm)
11914
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
11915 11916 11917
    return snapshot;
}

11918 11919
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
11920 11921 11922 11923 11924 11925
{
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

11926
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);
11927

11928
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
C
Chris Lalancette 已提交
11929 11930
        goto cleanup;

11931
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
C
Chris Lalancette 已提交
11932
        goto cleanup;
11933 11934

    virUUIDFormat(snapshot->domain->uuid, uuidstr);
C
Chris Lalancette 已提交
11935

11936
    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, flags, 0);
C
Chris Lalancette 已提交
11937 11938 11939

cleanup:
    if (vm)
11940
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
11941 11942 11943
    return xml;
}

11944 11945 11946 11947 11948 11949 11950 11951 11952 11953
static int
qemuDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;

    virCheckFlags(0, -1);

11954
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
11955 11956
        goto cleanup;

11957
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
11958 11959 11960 11961 11962 11963 11964
        goto cleanup;

    ret = (vm->current_snapshot &&
           STREQ(snapshot->name, vm->current_snapshot->def->name));

cleanup:
    if (vm)
11965
        virObjectUnlock(vm);
11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979
    return ret;
}


static int
qemuDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot,
                              unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;

    virCheckFlags(0, -1);

11980
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
11981 11982
        goto cleanup;

11983
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
11984 11985 11986 11987 11988 11989 11990 11991 11992
        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)
11993
        virObjectUnlock(vm);
11994 11995 11996
    return ret;
}

11997 11998
/* The domain is expected to be locked and inactive. */
static int
11999
qemuDomainSnapshotRevertInactive(virQEMUDriverPtr driver,
E
Eric Blake 已提交
12000
                                 virDomainObjPtr vm,
12001 12002 12003
                                 virDomainSnapshotObjPtr snap)
{
    /* Try all disks, but report failure if we skipped any.  */
E
Eric Blake 已提交
12004
    int ret = qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-a", true);
12005 12006 12007
    return ret > 0 ? -1 : ret;
}

C
Chris Lalancette 已提交
12008
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
12009
                                      unsigned int flags)
C
Chris Lalancette 已提交
12010
{
12011
    virQEMUDriverPtr driver = snapshot->domain->conn->privateData;
C
Chris Lalancette 已提交
12012 12013 12014 12015 12016
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainEventPtr event = NULL;
12017
    virDomainEventPtr event2 = NULL;
12018
    int detail;
C
Chris Lalancette 已提交
12019 12020
    qemuDomainObjPrivatePtr priv;
    int rc;
12021
    virDomainDefPtr config = NULL;
12022
    virQEMUDriverConfigPtr cfg = NULL;
C
Chris Lalancette 已提交
12023

12024
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
12025 12026
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED |
                  VIR_DOMAIN_SNAPSHOT_REVERT_FORCE, -1);
12027

12028 12029 12030 12031 12032 12033 12034 12035 12036 12037
    /* 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
12038 12039
     * Also, several transitions occur even if we fail partway through,
     * and use of FORCE can cause multiple transitions.
12040 12041
     */

C
Chris Lalancette 已提交
12042 12043
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
12044
    vm = virDomainObjListFindByUUID(driver->domains, snapshot->domain->uuid);
C
Chris Lalancette 已提交
12045
    if (!vm) {
12046 12047
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
C
Chris Lalancette 已提交
12048 12049
        goto cleanup;
    }
12050 12051 12052

    cfg = virQEMUDriverGetConfig(driver);

E
Eric Blake 已提交
12053 12054 12055 12056 12057
    if (virDomainHasDiskMirror(vm)) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE, "%s",
                       _("domain has active block copy job"));
        goto cleanup;
    }
C
Chris Lalancette 已提交
12058

12059
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
C
Chris Lalancette 已提交
12060 12061
        goto cleanup;

12062 12063 12064 12065 12066
    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) {
12067 12068 12069
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("transient domain needs to request run or pause "
                         "to revert to inactive snapshot"));
12070 12071
        goto cleanup;
    }
12072
    if (snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT) {
12073 12074 12075
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("revert to external disk snapshot not supported "
                         "yet"));
12076 12077
        goto cleanup;
    }
12078 12079
    if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_FORCE)) {
        if (!snap->def->dom) {
12080 12081 12082
            virReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY,
                           _("snapshot '%s' lacks domain '%s' rollback info"),
                           snap->def->name, vm->def->name);
12083 12084 12085 12086 12087 12088 12089
            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))) {
12090 12091
            virReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY, "%s",
                           _("must respawn qemu to start inactive snapshot"));
12092 12093 12094 12095
            goto cleanup;
        }
    }

12096

12097 12098 12099
    if (vm->current_snapshot) {
        vm->current_snapshot->def->current = false;
        if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
12100
                                            cfg->snapshotDir) < 0)
12101 12102 12103 12104 12105 12106
            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?  */
    }

12107
    /* Prepare to copy the snapshot inactive xml as the config of this
12108
     * domain.
12109 12110 12111
     *
     * XXX Should domain snapshots track live xml rather
     * than inactive xml?  */
12112
    snap->def->current = true;
12113
    if (snap->def->dom) {
12114
        config = virDomainDefCopy(driver->caps, snap->def->dom, true);
12115 12116 12117
        if (!config)
            goto cleanup;
    }
C
Chris Lalancette 已提交
12118

12119
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
12120 12121 12122 12123
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {
12124 12125 12126 12127 12128 12129 12130 12131 12132
        /* 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 已提交
12133
        if (virDomainObjIsActive(vm)) {
12134
            /* Transitions 5, 6, 8, 9 */
12135 12136
            /* Check for ABI compatibility.  */
            if (config && !virDomainDefCheckABIStability(vm->def, config)) {
12137 12138 12139 12140 12141
                virErrorPtr err = virGetLastError();

                if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_FORCE)) {
                    /* Re-spawn error using correct category. */
                    if (err->code == VIR_ERR_CONFIG_UNSUPPORTED)
12142 12143
                        virReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY, "%s",
                                       err->str2);
12144 12145 12146
                    goto endjob;
                }
                virResetError(err);
12147 12148
                qemuProcessStop(driver, vm,
                                VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
12149 12150 12151 12152 12153 12154 12155 12156
                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;
12157 12158
            }

C
Chris Lalancette 已提交
12159
            priv = vm->privateData;
12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174
            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)) {
12175 12176
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("guest unexpectedly quit"));
12177 12178 12179
                    goto endjob;
                }
            }
12180
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
12181 12182
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
12183 12184 12185
            if (rc < 0) {
                /* XXX resume domain if it was running before the
                 * failed loadvm attempt? */
12186
                goto endjob;
12187
            }
12188
            if (config)
12189
                virDomainObjAssignDef(vm, config, false, NULL);
E
Eric Blake 已提交
12190
        } else {
12191
            /* Transitions 2, 3 */
12192
        load:
12193
            was_stopped = true;
12194
            if (config)
12195
                virDomainObjAssignDef(vm, config, false, NULL);
12196

12197 12198 12199 12200
            rc = qemuProcessStart(snapshot->domain->conn,
                                  driver, vm, NULL, -1, NULL, snap,
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
                                  VIR_QEMU_PROCESS_START_PAUSED);
12201
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
12202 12203 12204 12205
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
C
Chris Lalancette 已提交
12206
            if (rc < 0)
12207
                goto endjob;
C
Chris Lalancette 已提交
12208 12209
        }

12210
        /* Touch up domain state.  */
12211 12212 12213
        if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING) &&
            (snap->def->state == VIR_DOMAIN_PAUSED ||
             (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226
            /* 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)) {
12227 12228
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("guest unexpectedly quit"));
12229 12230 12231 12232 12233
                goto endjob;
            }
            rc = qemuProcessStartCPUs(driver, vm, snapshot->domain->conn,
                                      VIR_DOMAIN_RUNNING_FROM_SNAPSHOT,
                                      QEMU_ASYNC_JOB_NONE);
H
Hu Tao 已提交
12234
            if (rc < 0)
12235
                goto endjob;
12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250
            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 已提交
12251
        }
E
Eric Blake 已提交
12252
    } else {
12253
        /* Transitions 1, 4, 7 */
12254 12255 12256
        /* 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 已提交
12257 12258 12259
         */

        if (virDomainObjIsActive(vm)) {
12260
            /* Transitions 4, 7 */
12261
            qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
12262
            virDomainAuditStop(vm, "from-snapshot");
12263
            detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
C
Chris Lalancette 已提交
12264 12265
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
12266
                                             detail);
12267 12268
        }

E
Eric Blake 已提交
12269
        if (qemuDomainSnapshotRevertInactive(driver, vm, snap) < 0) {
12270
            if (!vm->persistent) {
12271
                if (qemuDomainObjEndJob(driver, vm) > 0)
12272
                    qemuDomainRemoveInactive(driver, vm);
12273
                vm = NULL;
12274
                goto cleanup;
12275
            }
12276
            goto endjob;
C
Chris Lalancette 已提交
12277
        }
12278
        if (config)
12279
            virDomainObjAssignDef(vm, config, false, NULL);
12280

12281 12282 12283 12284
        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;
12285 12286 12287
            unsigned int start_flags = 0;

            start_flags |= paused ? VIR_QEMU_PROCESS_START_PAUSED : 0;
12288 12289 12290

            if (event)
                qemuDomainEventQueue(driver, event);
12291 12292 12293 12294
            rc = qemuProcessStart(snapshot->domain->conn,
                                  driver, vm, NULL, -1, NULL, NULL,
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
                                  start_flags);
12295 12296 12297 12298
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
            if (rc < 0) {
                if (!vm->persistent) {
                    if (qemuDomainObjEndJob(driver, vm) > 0)
12299
                        qemuDomainRemoveInactive(driver, vm);
12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315
                    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 已提交
12316 12317 12318 12319
    }

    ret = 0;

12320
endjob:
12321
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
12322 12323
        vm = NULL;

12324
cleanup:
12325 12326
    if (vm && ret == 0) {
        if (qemuDomainSnapshotWriteMetadata(vm, snap,
12327
                                            cfg->snapshotDir) < 0)
12328 12329 12330 12331 12332 12333
            ret = -1;
        else
            vm->current_snapshot = snap;
    } else if (snap) {
        snap->def->current = false;
    }
12334
    if (event) {
C
Chris Lalancette 已提交
12335
        qemuDomainEventQueue(driver, event);
12336 12337 12338
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
C
Chris Lalancette 已提交
12339
    if (vm)
12340
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12341
    qemuDriverUnlock(driver);
12342
    virObjectUnref(cfg);
C
Chris Lalancette 已提交
12343 12344 12345 12346

    return ret;
}

12347 12348 12349 12350

typedef struct _virQEMUSnapReparent virQEMUSnapReparent;
typedef virQEMUSnapReparent *virQEMUSnapReparentPtr;
struct _virQEMUSnapReparent {
12351
    virQEMUDriverConfigPtr cfg;
12352
    virDomainSnapshotObjPtr parent;
12353 12354
    virDomainObjPtr vm;
    int err;
12355
    virDomainSnapshotObjPtr last;
12356 12357 12358 12359
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
12360
                                   const void *name ATTRIBUTE_UNUSED,
12361 12362 12363
                                   void *data)
{
    virDomainSnapshotObjPtr snap = payload;
12364
    virQEMUSnapReparentPtr rep = data;
12365 12366 12367 12368 12369

    if (rep->err < 0) {
        return;
    }

12370
    VIR_FREE(snap->def->parent);
12371
    snap->parent = rep->parent;
12372

12373
    if (rep->parent->def) {
12374
        snap->def->parent = strdup(rep->parent->def->name);
12375

12376 12377 12378 12379
        if (snap->def->parent == NULL) {
            virReportOOMError();
            rep->err = -1;
            return;
12380 12381
        }
    }
12382

12383 12384 12385
    if (!snap->sibling)
        rep->last = snap;

12386
    rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
12387
                                               rep->cfg->snapshotDir);
12388 12389
}

12390

C
Chris Lalancette 已提交
12391 12392 12393
static int qemuDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                                    unsigned int flags)
{
12394
    virQEMUDriverPtr driver = snapshot->domain->conn->privateData;
C
Chris Lalancette 已提交
12395 12396 12397 12398
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
12399 12400
    virQEMUSnapRemove rem;
    virQEMUSnapReparent rep;
12401
    bool metadata_only = !!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY);
12402
    int external = 0;
12403
    virQEMUDriverConfigPtr cfg = NULL;
C
Chris Lalancette 已提交
12404

12405
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
12406 12407
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY |
                  VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, -1);
12408

C
Chris Lalancette 已提交
12409 12410
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
12411
    vm = virDomainObjListFindByUUID(driver->domains, snapshot->domain->uuid);
C
Chris Lalancette 已提交
12412
    if (!vm) {
12413 12414
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
C
Chris Lalancette 已提交
12415 12416 12417
        goto cleanup;
    }

12418
    cfg = virQEMUDriverGetConfig(driver);
12419
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
C
Chris Lalancette 已提交
12420 12421
        goto cleanup;

12422
    if (!metadata_only) {
12423
        if (!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) &&
12424
            virDomainSnapshotIsExternal(snap))
12425 12426
            external++;
        if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
E
Eric Blake 已提交
12427
            virDomainSnapshotForEachDescendant(snap,
12428 12429 12430
                                               qemuDomainSnapshotCountExternal,
                                               &external);
        if (external) {
12431 12432 12433
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("deletion of %d external disk snapshots not "
                             "supported yet"), external);
12434 12435 12436 12437
            goto cleanup;
        }
    }

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

12441 12442
    if (flags & (VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                 VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)) {
C
Chris Lalancette 已提交
12443 12444
        rem.driver = driver;
        rem.vm = vm;
12445
        rem.metadata_only = metadata_only;
C
Chris Lalancette 已提交
12446
        rem.err = 0;
12447
        rem.current = false;
E
Eric Blake 已提交
12448
        virDomainSnapshotForEachDescendant(snap,
E
Eric Blake 已提交
12449
                                           qemuDomainSnapshotDiscardAll,
12450
                                           &rem);
C
Chris Lalancette 已提交
12451
        if (rem.err < 0)
12452
            goto endjob;
12453 12454 12455 12456
        if (rem.current) {
            if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
                snap->def->current = true;
                if (qemuDomainSnapshotWriteMetadata(vm, snap,
12457
                                                    cfg->snapshotDir) < 0) {
12458 12459 12460
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("failed to set snapshot '%s' as current"),
                                   snap->def->name);
12461 12462 12463 12464
                    snap->def->current = false;
                    goto endjob;
                }
            }
12465
            vm->current_snapshot = snap;
12466
        }
12467
    } else if (snap->nchildren) {
12468
        rep.cfg = cfg;
12469
        rep.parent = snap->parent;
12470 12471
        rep.vm = vm;
        rep.err = 0;
12472
        rep.last = NULL;
E
Eric Blake 已提交
12473
        virDomainSnapshotForEachChild(snap,
12474 12475
                                      qemuDomainSnapshotReparentChildren,
                                      &rep);
12476 12477
        if (rep.err < 0)
            goto endjob;
12478
        /* Can't modify siblings during ForEachChild, so do it now.  */
12479 12480 12481
        snap->parent->nchildren += snap->nchildren;
        rep.last->sibling = snap->parent->first_child;
        snap->parent->first_child = snap->first_child;
C
Chris Lalancette 已提交
12482 12483
    }

12484 12485 12486
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
        snap->nchildren = 0;
        snap->first_child = NULL;
12487
        ret = 0;
12488
    } else {
12489
        virDomainSnapshotDropParent(snap);
12490
        ret = qemuDomainSnapshotDiscard(driver, vm, snap, true, metadata_only);
12491
    }
C
Chris Lalancette 已提交
12492

12493
endjob:
12494
    if (qemuDomainObjEndJob(driver, vm) == 0)
12495 12496
        vm = NULL;

C
Chris Lalancette 已提交
12497 12498
cleanup:
    if (vm)
12499
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12500
    qemuDriverUnlock(driver);
12501
    virObjectUnref(cfg);
C
Chris Lalancette 已提交
12502 12503
    return ret;
}
12504

12505 12506 12507
static int qemuDomainMonitorCommand(virDomainPtr domain, const char *cmd,
                                    char **result, unsigned int flags)
{
12508
    virQEMUDriverPtr driver = domain->conn->privateData;
12509 12510 12511
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
12512
    bool hmp;
12513

12514
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
12515

12516
    if (!(vm = qemuDomObjFromDomain(domain)))
12517 12518 12519
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
12520 12521
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
12522
        goto cleanup;
12523
    }
12524

12525
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
12526 12527 12528
        goto cleanup;

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

12534 12535
    priv = vm->privateData;

12536
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
12537

12538 12539
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

12540
    qemuDomainObjEnterMonitor(driver, vm);
12541
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
12542
    qemuDomainObjExitMonitor(driver, vm);
12543 12544

endjob:
12545
    if (qemuDomainObjEndJob(driver, vm) == 0) {
12546 12547 12548 12549 12550
        vm = NULL;
    }

cleanup:
    if (vm)
12551
        virObjectUnlock(vm);
12552 12553 12554
    return ret;
}

12555

12556
static virDomainPtr qemuDomainAttach(virConnectPtr conn,
12557
                                     unsigned int pid_value,
12558 12559
                                     unsigned int flags)
{
12560
    virQEMUDriverPtr driver = conn->privateData;
12561 12562 12563 12564 12565
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainPtr dom = NULL;
    virDomainChrSourceDefPtr monConfig = NULL;
    bool monJSON = false;
12566
    pid_t pid = pid_value;
12567
    char *pidfile = NULL;
12568
    qemuCapsPtr caps = NULL;
12569 12570 12571 12572 12573 12574 12575 12576 12577 12578

    virCheckFlags(0, NULL);

    qemuDriverLock(driver);

    if (!(def = qemuParseCommandLinePid(driver->caps, pid,
                                        &pidfile, &monConfig, &monJSON)))
        goto cleanup;

    if (!monConfig) {
12579 12580
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("No monitor connection for pid %u"), pid_value);
12581 12582 12583
        goto cleanup;
    }
    if (monConfig->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
12584 12585 12586 12587 12588
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Cannot connect to monitor connection of type '%s' "
                         "for pid %u"),
                       virDomainChrTypeToString(monConfig->type),
                       pid_value);
12589 12590 12591 12592
        goto cleanup;
    }

    if (!(def->name) &&
12593
        virAsprintf(&def->name, "attach-pid-%u", pid_value) < 0) {
12594 12595 12596 12597
        virReportOOMError();
        goto cleanup;
    }

12598 12599 12600
    if (!(caps = qemuCapsCacheLookup(driver->capsCache, def->emulator)))
        goto cleanup;

12601
    if (qemuCanonicalizeMachine(def, caps) < 0)
12602 12603
        goto cleanup;

12604
    if (qemuDomainAssignAddresses(def, caps, NULL) < 0)
12605 12606
        goto cleanup;

12607 12608
    if (!(vm = virDomainObjListAdd(driver->domains,
                                   driver->caps,
12609 12610 12611 12612
                                   def,
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
12613 12614 12615 12616
        goto cleanup;

    def = NULL;

12617
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631
        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:
12632
    if (qemuDomainObjEndJob(driver, vm) == 0) {
12633 12634 12635 12636 12637 12638
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
12639
    virObjectUnref(caps);
12640 12641
    virDomainChrSourceDefFree(monConfig);
    if (vm)
12642
        virObjectUnlock(vm);
12643 12644 12645 12646 12647 12648
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


12649 12650
static int
qemuDomainOpenConsole(virDomainPtr dom,
12651
                      const char *dev_name,
12652 12653 12654 12655 12656 12657 12658
                      virStreamPtr st,
                      unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    int i;
    virDomainChrDefPtr chr = NULL;
12659
    qemuDomainObjPrivatePtr priv;
12660

12661 12662
    virCheckFlags(VIR_DOMAIN_CONSOLE_SAFE |
                  VIR_DOMAIN_CONSOLE_FORCE, -1);
12663

12664
    if (!(vm = qemuDomObjFromDomain(dom)))
12665 12666 12667
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
12668 12669
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
12670 12671 12672
        goto cleanup;
    }

12673 12674
    priv = vm->privateData;

12675
    if (dev_name) {
12676 12677 12678 12679 12680
        for (i = 0 ; !chr && i < vm->def->nconsoles ; i++) {
            if (vm->def->consoles[i]->info.alias &&
                STREQ(dev_name, vm->def->consoles[i]->info.alias))
                chr = vm->def->consoles[i];
        }
12681
        for (i = 0 ; !chr && i < vm->def->nserials ; i++) {
12682
            if (STREQ(dev_name, vm->def->serials[i]->info.alias))
12683 12684 12685
                chr = vm->def->serials[i];
        }
        for (i = 0 ; !chr && i < vm->def->nparallels ; i++) {
12686
            if (STREQ(dev_name, vm->def->parallels[i]->info.alias))
12687 12688 12689
                chr = vm->def->parallels[i];
        }
    } else {
12690 12691
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
12692 12693 12694 12695 12696
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
12697 12698 12699
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find character device %s"),
                       NULLSTR(dev_name));
12700 12701 12702
        goto cleanup;
    }

12703
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
12704 12705 12706
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
                       NULLSTR(dev_name));
12707 12708 12709
        goto cleanup;
    }

12710
    /* handle mutually exclusive access to console devices */
12711
    ret = virChrdevOpen(priv->devs,
12712
                        &chr->source,
12713 12714
                        st,
                        (flags & VIR_DOMAIN_CONSOLE_FORCE) != 0);
12715 12716

    if (ret == 1) {
12717 12718
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Active console session exists for this domain"));
12719 12720
        ret = -1;
    }
12721 12722 12723

cleanup:
    if (vm)
12724
        virObjectUnlock(vm);
12725 12726 12727
    return ret;
}

12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795
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;

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

    priv = vm->privateData;

    if (name) {
        for (i = 0 ; !chr && i < vm->def->nchannels ; i++) {
            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)
12796
        virObjectUnlock(vm);
12797 12798 12799
    return ret;
}

E
Eric Blake 已提交
12800
static char *
E
Eric Blake 已提交
12801
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path, int *idx)
E
Eric Blake 已提交
12802
{
12803 12804
    int i;
    char *ret = NULL;
12805
    virDomainDiskDefPtr disk;
12806

12807 12808 12809
    i = virDomainDiskIndexByName(vm->def, path, true);
    if (i < 0)
        goto cleanup;
12810

12811
    disk = vm->def->disks[i];
E
Eric Blake 已提交
12812 12813
    if (idx)
        *idx = i;
12814

12815 12816 12817 12818 12819 12820 12821 12822
    if (disk->type != VIR_DOMAIN_DISK_TYPE_BLOCK &&
        disk->type != VIR_DOMAIN_DISK_TYPE_FILE)
        goto cleanup;

    if (disk->src) {
        if (virAsprintf(&ret, "drive-%s", disk->info.alias) < 0) {
            virReportOOMError();
            return NULL;
12823 12824 12825
        }
    }

12826
cleanup:
12827
    if (!ret) {
12828 12829
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("No device found for specified path"));
12830 12831 12832 12833
    }
    return ret;
}

12834 12835 12836 12837
/* 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 已提交
12838
qemuDomainBlockPivot(virConnectPtr conn,
12839
                     virQEMUDriverPtr driver, virDomainObjPtr vm,
12840 12841 12842 12843 12844 12845
                     const char *device, virDomainDiskDefPtr disk)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainBlockJobInfo info;
    const char *format = virStorageFileFormatTypeToString(disk->mirrorFormat);
E
Eric Blake 已提交
12846
    bool resume = false;
12847 12848 12849 12850
    virCgroupPtr cgroup = NULL;
    char *oldsrc = NULL;
    int oldformat;
    virStorageFileMetadataPtr oldchain = NULL;
12851
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877

    /* Probe the status, if needed.  */
    if (!disk->mirroring) {
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        ret = qemuMonitorBlockJob(priv->mon, device, NULL, 0, &info,
                                  BLOCK_JOB_INFO, true);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
        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 已提交
12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900
    /* 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;
        }
    }

12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927
    /* 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.  */
    if (disk->mirrorFormat && disk->mirrorFormat != VIR_STORAGE_FILE_RAW &&
        qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES) &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to find cgroup for %s"),
                       vm->def->name);
        goto cleanup;
    }
    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 &&
12928
        (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
12929 12930 12931 12932 12933 12934 12935 12936 12937 12938
                                 vm, disk) < 0 ||
         (cgroup && qemuSetupDiskCgroup(vm, cgroup, disk) < 0) ||
         virSecurityManagerSetImageLabel(driver->securityManager, vm->def,
                                         disk) < 0)) {
        disk->src = oldsrc;
        disk->format = oldformat;
        disk->backingChain = oldchain;
        goto cleanup;
    }

12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951
    /* Attempt the pivot.  */
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorDrivePivot(priv->mon, device, disk->mirror, format);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    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.  */
12952 12953
        VIR_FREE(oldsrc);
        virStorageFileFreeMetadata(oldchain);
12954 12955 12956 12957 12958 12959 12960 12961 12962 12963
        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.  */
12964 12965 12966 12967
        disk->src = oldsrc;
        disk->format = oldformat;
        virStorageFileFreeMetadata(disk->backingChain);
        disk->backingChain = oldchain;
12968 12969
        VIR_FREE(disk->mirror);
    }
12970 12971
    disk->mirrorFormat = VIR_STORAGE_FILE_NONE;
    disk->mirroring = false;
12972 12973

cleanup:
12974 12975
    if (cgroup)
        virCgroupFree(&cgroup);
E
Eric Blake 已提交
12976 12977 12978
    if (resume && virDomainObjIsActive(vm) &&
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED,
12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989
                             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 已提交
12990
    }
12991
    virObjectUnref(cfg);
12992 12993 12994
    return ret;
}

12995
static int
12996
qemuDomainBlockJobImpl(virDomainPtr dom, const char *path, const char *base,
12997
                       unsigned long bandwidth, virDomainBlockJobInfoPtr info,
12998
                       int mode, unsigned int flags)
12999
{
13000
    virQEMUDriverPtr driver = dom->conn->privateData;
13001 13002 13003
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
E
Eric Blake 已提交
13004
    char *device = NULL;
13005
    int ret = -1;
13006
    bool async = false;
13007 13008 13009
    virDomainEventPtr event = NULL;
    int idx;
    virDomainDiskDefPtr disk;
13010 13011 13012

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
13013
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
13014
    if (!vm) {
13015 13016
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
13017 13018
        goto cleanup;
    }
13019
    if (!virDomainObjIsActive(vm)) {
13020 13021
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
13022 13023 13024
        goto cleanup;
    }

13025
    priv = vm->privateData;
13026
    if (qemuCapsGet(priv->caps, QEMU_CAPS_BLOCKJOB_ASYNC)) {
13027
        async = true;
13028
    } else if (!qemuCapsGet(priv->caps, QEMU_CAPS_BLOCKJOB_SYNC)) {
13029 13030
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block jobs not supported with this QEMU binary"));
13031 13032
        goto cleanup;
    } else if (base) {
13033 13034 13035
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("partial block pull not supported with this "
                         "QEMU binary"));
13036
        goto cleanup;
13037
    } else if (mode == BLOCK_JOB_PULL && bandwidth) {
13038 13039 13040
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("setting bandwidth at start of block pull not "
                         "supported with this QEMU binary"));
13041
        goto cleanup;
13042
    }
13043

13044 13045
    device = qemuDiskPathToAlias(vm, path, &idx);
    if (!device)
13046
        goto cleanup;
13047
    disk = vm->def->disks[idx];
13048

E
Eric Blake 已提交
13049 13050 13051 13052 13053 13054
    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;
    }
13055 13056 13057 13058 13059 13060 13061 13062
    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 已提交
13063

13064 13065
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
13066 13067

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

13073 13074
    if (disk->mirror && mode == BLOCK_JOB_ABORT &&
        (flags & VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT)) {
E
Eric Blake 已提交
13075
        ret = qemuDomainBlockPivot(dom->conn, driver, vm, device, disk);
13076 13077 13078
        goto endjob;
    }

13079
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
13080
    /* XXX - libvirt should really be tracking the backing file chain
13081 13082
     * itself, and validating that base is on the chain, rather than
     * relying on qemu to do this.  */
13083 13084
    ret = qemuMonitorBlockJob(priv->mon, device, base, bandwidth, info, mode,
                              async);
13085
    qemuDomainObjExitMonitorWithDriver(driver, vm);
13086 13087 13088
    if (ret < 0)
        goto endjob;

13089 13090 13091 13092 13093 13094
    /* 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;

13095 13096 13097 13098 13099 13100 13101 13102 13103
    /* 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;
    }

13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130
    /* 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;

                qemuDomainObjEnterMonitorWithDriver(driver, vm);
                ret = qemuMonitorBlockJob(priv->mon, device, NULL, 0, &dummy,
                                          BLOCK_JOB_INFO, async);
                qemuDomainObjExitMonitorWithDriver(driver, vm);

                if (ret <= 0)
                    break;

13131
                virObjectUnlock(vm);
13132 13133 13134 13135 13136
                qemuDriverUnlock(driver);

                nanosleep(&ts, NULL);

                qemuDriverLock(driver);
13137
                virObjectLock(vm);
13138 13139

                if (!virDomainObjIsActive(vm)) {
13140 13141
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("domain is not running"));
13142 13143 13144 13145 13146 13147
                    ret = -1;
                    break;
                }
            }
        }
    }
13148 13149

endjob:
13150 13151 13152 13153 13154 13155 13156 13157
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    VIR_FREE(device);
    if (vm)
13158
        virObjectUnlock(vm);
13159 13160
    if (event)
        qemuDomainEventQueue(driver, event);
13161 13162 13163 13164 13165 13166 13167
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainBlockJobAbort(virDomainPtr dom, const char *path, unsigned int flags)
{
13168 13169
    virCheckFlags(VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC |
                  VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT, -1);
13170 13171
    return qemuDomainBlockJobImpl(dom, path, NULL, 0, NULL, BLOCK_JOB_ABORT,
                                  flags);
13172 13173 13174 13175 13176 13177 13178
}

static int
qemuDomainGetBlockJobInfo(virDomainPtr dom, const char *path,
                           virDomainBlockJobInfoPtr info, unsigned int flags)
{
    virCheckFlags(0, -1);
13179 13180
    return qemuDomainBlockJobImpl(dom, path, NULL, 0, info, BLOCK_JOB_INFO,
                                  flags);
13181 13182 13183 13184 13185 13186 13187
}

static int
qemuDomainBlockJobSetSpeed(virDomainPtr dom, const char *path,
                           unsigned long bandwidth, unsigned int flags)
{
    virCheckFlags(0, -1);
13188
    return qemuDomainBlockJobImpl(dom, path, NULL, bandwidth, NULL,
13189
                                  BLOCK_JOB_SPEED, flags);
13190 13191
}

13192 13193 13194 13195 13196
static int
qemuDomainBlockCopy(virDomainPtr dom, const char *path,
                    const char *dest, const char *format,
                    unsigned long bandwidth, unsigned int flags)
{
13197
    virQEMUDriverPtr driver = dom->conn->privateData;
13198 13199 13200 13201 13202 13203
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *device = NULL;
    virDomainDiskDefPtr disk;
    int ret = -1;
    int idx;
13204
    struct stat st;
13205 13206 13207
    bool need_unlink = false;
    char *mirror = NULL;
    virCgroupPtr cgroup = NULL;
13208
    virQEMUDriverConfigPtr cfg = NULL;
13209 13210

    /* Preliminaries: find the disk we are editing, sanity checks */
13211 13212
    virCheckFlags(VIR_DOMAIN_BLOCK_REBASE_SHALLOW |
                  VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT, -1);
13213 13214 13215 13216

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
    priv = vm->privateData;
13217
    cfg = virQEMUDriverGetConfig(driver);
13218 13219 13220 13221 13222
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
        goto cleanup;
    }
13223 13224 13225 13226 13227 13228 13229
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES) &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to find cgroup for %s"),
                       vm->def->name);
        goto cleanup;
    }
13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280

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

    if (!(qemuCapsGet(priv->caps, QEMU_CAPS_DRIVE_MIRROR) &&
          qemuCapsGet(priv->caps, QEMU_CAPS_BLOCKJOB_ASYNC))) {
        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.  */
13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300
    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;
    }

13301 13302 13303 13304 13305 13306 13307
    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)
13308
            disk->mirrorFormat = disk->format;
13309
    } else if (format) {
13310 13311 13312 13313 13314 13315
        disk->mirrorFormat = virStorageFileFormatTypeFromString(format);
        if (disk->mirrorFormat <= 0) {
            virReportError(VIR_ERR_INVALID_ARG, _("unrecognized format '%s'"),
                           format);
            goto endjob;
        }
13316 13317 13318 13319 13320
    } 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.  */
13321 13322
        disk->mirrorFormat = virStorageFileProbeFormat(dest, cfg->user,
                                                       cfg->group);
13323 13324 13325
    }
    if (!format && disk->mirrorFormat > 0)
        format = virStorageFileFormatTypeToString(disk->mirrorFormat);
13326
    if (!(mirror = strdup(dest))) {
13327 13328 13329 13330
        virReportOOMError();
        goto endjob;
    }

13331 13332 13333 13334 13335 13336 13337
    if (qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, dest,
                                          VIR_DISK_CHAIN_READ_WRITE) < 0) {
        qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, dest,
                                          VIR_DISK_CHAIN_NO_ACCESS);
        goto endjob;
    }

13338 13339 13340 13341
    /* Actually start the mirroring */
    qemuDomainObjEnterMonitor(driver, vm);
    ret = qemuMonitorDriveMirror(priv->mon, device, dest, format, bandwidth,
                                 flags);
13342
    virDomainAuditDisk(vm, NULL, dest, "mirror", ret >= 0);
13343
    qemuDomainObjExitMonitor(driver, vm);
13344 13345 13346 13347 13348 13349 13350 13351 13352 13353
    if (ret < 0) {
        qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, dest,
                                          VIR_DISK_CHAIN_NO_ACCESS);
        goto endjob;
    }

    /* Update vm in place to match changes.  */
    need_unlink = false;
    disk->mirror = mirror;
    mirror = NULL;
13354 13355

endjob:
13356 13357 13358
    if (need_unlink && unlink(dest))
        VIR_WARN("unable to unlink just-created %s", dest);
    if (ret < 0)
13359
        disk->mirrorFormat = VIR_STORAGE_FILE_NONE;
13360
    VIR_FREE(mirror);
13361 13362 13363 13364 13365 13366
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
13367 13368
    if (cgroup)
        virCgroupFree(&cgroup);
13369 13370
    VIR_FREE(device);
    if (vm)
13371
        virObjectUnlock(vm);
13372
    virObjectUnref(cfg);
13373 13374 13375
    return ret;
}

13376
static int
13377 13378
qemuDomainBlockRebase(virDomainPtr dom, const char *path, const char *base,
                      unsigned long bandwidth, unsigned int flags)
13379
{
13380
    virCheckFlags(VIR_DOMAIN_BLOCK_REBASE_SHALLOW |
13381
                  VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT |
13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393
                  VIR_DOMAIN_BLOCK_REBASE_COPY |
                  VIR_DOMAIN_BLOCK_REBASE_COPY_RAW, -1);

    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);
        return qemuDomainBlockCopy(dom, path, base, format, bandwidth, flags);
    }

13394 13395
    return qemuDomainBlockJobImpl(dom, path, base, bandwidth, NULL,
                                  BLOCK_JOB_PULL, flags);
13396
}
13397

13398 13399 13400 13401
static int
qemuDomainBlockPull(virDomainPtr dom, const char *path, unsigned long bandwidth,
                    unsigned int flags)
{
13402 13403 13404
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, NULL, bandwidth, NULL,
                                  BLOCK_JOB_PULL, flags);
13405 13406
}

13407 13408 13409 13410 13411 13412

static int
qemuDomainBlockCommit(virDomainPtr dom, const char *path, const char *base,
                      const char *top, unsigned long bandwidth,
                      unsigned int flags)
{
13413
    virQEMUDriverPtr driver = dom->conn->privateData;
13414 13415 13416 13417 13418
    qemuDomainObjPrivatePtr priv;
    virDomainObjPtr vm = NULL;
    char *device = NULL;
    int ret = -1;
    int idx;
E
Eric Blake 已提交
13419
    virDomainDiskDefPtr disk = NULL;
13420 13421 13422 13423
    const char *top_canon = NULL;
    virStorageFileMetadataPtr top_meta = NULL;
    const char *top_parent = NULL;
    const char *base_canon = NULL;
13424
    virCgroupPtr cgroup = NULL;
E
Eric Blake 已提交
13425
    bool clean_access = false;
13426

13427
    virCheckFlags(VIR_DOMAIN_BLOCK_COMMIT_SHALLOW, -1);
13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
    priv = vm->privateData;

    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 (!qemuCapsGet(priv->caps, QEMU_CAPS_BLOCK_COMMIT)) {
        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;
    }
13458 13459
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto endjob;
13460

13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499
    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;
    }
13500

13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514
    /* 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.  */
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES) &&
        virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to find cgroup for %s"),
                       vm->def->name);
        goto endjob;
    }
E
Eric Blake 已提交
13515
    clean_access = true;
13516 13517 13518 13519 13520 13521 13522 13523 13524
    if (qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, base_canon,
                                          VIR_DISK_CHAIN_READ_WRITE) < 0 ||
        (top_parent && top_parent != disk->src &&
         qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk,
                                           top_parent,
                                           VIR_DISK_CHAIN_READ_WRITE) < 0))
        goto endjob;

    /* Start the commit operation.  */
13525
    qemuDomainObjEnterMonitor(driver, vm);
13526 13527
    ret = qemuMonitorBlockCommit(priv->mon, device, top_canon, base_canon,
                                 bandwidth);
13528 13529 13530
    qemuDomainObjExitMonitor(driver, vm);

endjob:
E
Eric Blake 已提交
13531
    if (ret < 0 && clean_access) {
13532 13533 13534 13535 13536 13537 13538 13539 13540 13541
        /* Revert access to read-only, if possible.  */
        qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk, base_canon,
                                          VIR_DISK_CHAIN_READ_ONLY);
        if (top_parent && top_parent != disk->src)
            qemuDomainPrepareDiskChainElement(driver, vm, cgroup, disk,
                                              top_parent,
                                              VIR_DISK_CHAIN_READ_ONLY);
    }
    if (cgroup)
        virCgroupFree(&cgroup);
13542 13543 13544 13545 13546 13547 13548 13549
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    VIR_FREE(device);
    if (vm)
13550
        virObjectUnlock(vm);
13551 13552 13553
    return ret;
}

13554 13555 13556 13557 13558 13559
static int
qemuDomainOpenGraphics(virDomainPtr dom,
                       unsigned int idx,
                       int fd,
                       unsigned int flags)
{
13560
    virQEMUDriverPtr driver = dom->conn->privateData;
13561 13562 13563 13564 13565 13566 13567 13568 13569 13570
    virDomainObjPtr vm = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
    const char *protocol;

    virCheckFlags(VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH, -1);

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
13571
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
13572
    if (!vm) {
13573 13574
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
13575 13576 13577 13578
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
13579 13580
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
13581 13582 13583 13584 13585 13586
        goto cleanup;
    }

    priv = vm->privateData;

    if (idx >= vm->def->ngraphics) {
13587 13588
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No graphics backend with index %d"), idx);
13589 13590 13591 13592 13593 13594 13595 13596 13597 13598
        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:
13599 13600 13601
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Can only open VNC or SPICE graphics backends, not %s"),
                       virDomainGraphicsTypeToString(vm->def->graphics[idx]->type));
13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorOpenGraphics(priv->mon, protocol, fd, "graphicsfd",
                                  (flags & VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH) != 0);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
13618
        virObjectUnlock(vm);
13619 13620 13621 13622
    qemuDriverUnlock(driver);
    return ret;
}

13623 13624 13625 13626 13627 13628 13629
static int
qemuDomainSetBlockIoTune(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int nparams,
                         unsigned int flags)
{
13630
    virQEMUDriverPtr driver = dom->conn->privateData;
13631 13632 13633 13634
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virDomainDefPtr persistentDef = NULL;
    virDomainBlockIoTuneInfo info;
E
Eric Blake 已提交
13635
    virDomainBlockIoTuneInfo *oldinfo;
13636 13637 13638 13639 13640
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    const char *device = NULL;
    int ret = -1;
    int i;
    int idx = -1;
E
Eric Blake 已提交
13641 13642
    bool set_bytes = false;
    bool set_iops = false;
13643
    virQEMUDriverConfigPtr cfg = NULL;
13644 13645 13646

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661
    if (virTypedParameterArrayValidate(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)
        return -1;
13662 13663 13664 13665 13666

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

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
13667
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
13668
    if (!vm) {
13669 13670
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
13671 13672
        goto cleanup;
    }
13673
    priv = vm->privateData;
13674 13675
    cfg = virQEMUDriverGetConfig(driver);

13676
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_DRIVE_IOTUNE)) {
13677 13678 13679
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block I/O throttling not supported with this "
                         "QEMU binary"));
13680 13681
        goto cleanup;
    }
13682

E
Eric Blake 已提交
13683
    device = qemuDiskPathToAlias(vm, disk, &idx);
13684 13685 13686 13687 13688 13689 13690
    if (!device) {
        goto cleanup;
    }

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

13691 13692
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
13693 13694 13695 13696 13697 13698 13699
        goto endjob;

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

        if (STREQ(param->field, VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC)) {
            info.total_bytes_sec = param->value.ul;
E
Eric Blake 已提交
13700
            set_bytes = true;
13701 13702 13703
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC)) {
            info.read_bytes_sec = param->value.ul;
E
Eric Blake 已提交
13704
            set_bytes = true;
13705 13706 13707
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC)) {
            info.write_bytes_sec = param->value.ul;
E
Eric Blake 已提交
13708
            set_bytes = true;
13709 13710 13711
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC)) {
            info.total_iops_sec = param->value.ul;
E
Eric Blake 已提交
13712
            set_iops = true;
13713 13714 13715
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC)) {
            info.read_iops_sec = param->value.ul;
E
Eric Blake 已提交
13716
            set_iops = true;
13717 13718 13719
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC)) {
            info.write_iops_sec = param->value.ul;
E
Eric Blake 已提交
13720
            set_iops = true;
13721 13722 13723 13724 13725
        }
    }

    if ((info.total_bytes_sec && info.read_bytes_sec) ||
        (info.total_bytes_sec && info.write_bytes_sec)) {
13726 13727
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("total and read/write of bytes_sec cannot be set at the same time"));
13728 13729 13730 13731 13732
        goto endjob;
    }

    if ((info.total_iops_sec && info.read_iops_sec) ||
        (info.total_iops_sec && info.write_iops_sec)) {
13733 13734
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("total and read/write of iops_sec cannot be set at the same time"));
13735 13736 13737 13738
        goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
E
Eric Blake 已提交
13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752
        /* 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;
        }
13753 13754 13755
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        ret = qemuMonitorSetBlockIoThrottle(priv->mon, device, &info);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
L
Lei Li 已提交
13756 13757
        if (ret < 0)
            goto endjob;
13758
        vm->def->disks[idx]->blkdeviotune = info;
13759 13760 13761
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
13762 13763 13764 13765
        sa_assert(persistentDef);
        idx = virDomainDiskIndexByName(persistentDef, disk, true);
        if (idx < 0)
            goto endjob;
E
Eric Blake 已提交
13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776
        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;
        }
13777
        persistentDef->disks[idx]->blkdeviotune = info;
13778
        ret = virDomainSaveConfig(cfg->configDir, persistentDef);
13779
        if (ret < 0) {
13780
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792
                           _("Write to config file failed"));
            goto endjob;
        }
    }

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

cleanup:
    VIR_FREE(device);
    if (vm)
13793
        virObjectUnlock(vm);
13794
    qemuDriverUnlock(driver);
13795
    virObjectUnref(cfg);
13796 13797 13798 13799 13800 13801 13802 13803 13804 13805
    return ret;
}

static int
qemuDomainGetBlockIoTune(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int *nparams,
                         unsigned int flags)
{
13806
    virQEMUDriverPtr driver = dom->conn->privateData;
13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virDomainDefPtr persistentDef = NULL;
    virDomainBlockIoTuneInfo reply;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    const char *device = NULL;
    int ret = -1;
    int i;

    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;

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
13825
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
13826
    if (!vm) {
13827 13828
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
13829 13830 13831 13832 13833 13834 13835 13836 13837 13838
        goto cleanup;
    }

    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 已提交
13839
    device = qemuDiskPathToAlias(vm, disk, NULL);
13840 13841 13842 13843 13844 13845 13846 13847

    if (!device) {
        goto cleanup;
    }

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

13848 13849
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        priv = vm->privateData;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        ret = qemuMonitorGetBlockIoThrottle(priv->mon, device, &reply);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
        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];

13871
        switch (i) {
13872
        case 0:
13873 13874 13875 13876
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.total_bytes_sec) < 0)
13877 13878 13879
                goto endjob;
            break;
        case 1:
13880 13881 13882 13883
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.read_bytes_sec) < 0)
13884 13885 13886
                goto endjob;
            break;
        case 2:
13887 13888 13889 13890
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.write_bytes_sec) < 0)
13891 13892 13893
                goto endjob;
            break;
        case 3:
13894 13895 13896 13897
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.total_iops_sec) < 0)
13898 13899 13900
                goto endjob;
            break;
        case 4:
13901 13902 13903 13904
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.read_iops_sec) < 0)
13905 13906 13907
                goto endjob;
            break;
        case 5:
13908 13909 13910 13911
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.write_iops_sec) < 0)
13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929
                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)
13930
        virObjectUnlock(vm);
13931 13932 13933
    qemuDriverUnlock(driver);
    return ret;
}
13934

13935 13936 13937 13938 13939 13940
static int
qemuDomainGetDiskErrors(virDomainPtr dom,
                        virDomainDiskErrorPtr errors,
                        unsigned int nerrors,
                        unsigned int flags)
{
13941
    virQEMUDriverPtr driver = dom->conn->privateData;
13942 13943 13944 13945 13946 13947 13948 13949 13950
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virHashTablePtr table = NULL;
    int ret = -1;
    int i;
    int n = 0;

    virCheckFlags(0, -1);

13951
    if (!(vm = qemuDomObjFromDomain(dom)))
13952 13953 13954 13955 13956 13957 13958 13959
        goto cleanup;

    priv = vm->privateData;

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

    if (!virDomainObjIsActive(vm)) {
13960 13961
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001
        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;

            if (!(errors[n].disk = strdup(disk->dst))) {
                virReportOOMError();
                goto endjob;
            }
            errors[n].error = info->io_status;
            n++;
        }
    }

    ret = n;

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

cleanup:
    if (vm)
14002
        virObjectUnlock(vm);
14003 14004 14005 14006 14007 14008 14009 14010
    virHashFree(table);
    if (ret < 0) {
        for (i = 0; i < n; i++)
            VIR_FREE(errors[i].disk);
    }
    return ret;
}

14011 14012 14013 14014 14015 14016 14017 14018
static int
qemuDomainSetMetadata(virDomainPtr dom,
                      int type,
                      const char *metadata,
                      const char *key ATTRIBUTE_UNUSED,
                      const char *uri ATTRIBUTE_UNUSED,
                      unsigned int flags)
{
14019
    virQEMUDriverPtr driver = dom->conn->privateData;
14020 14021 14022
    virDomainObjPtr vm;
    virDomainDefPtr persistentDef;
    int ret = -1;
14023
    virQEMUDriverConfigPtr cfg = NULL;
14024 14025 14026 14027

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

14028
    if (!(vm = qemuDomObjFromDomain(dom)))
14029 14030
        goto cleanup;

14031 14032
    cfg = virQEMUDriverGetConfig(driver);

14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        switch ((virDomainMetadataType) type) {
        case VIR_DOMAIN_METADATA_DESCRIPTION:
            VIR_FREE(vm->def->description);
            if (metadata &&
                !(vm->def->description = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_TITLE:
            VIR_FREE(vm->def->title);
            if (metadata &&
                !(vm->def->title = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_ELEMENT:
14052
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
14053
                           _("QEmu driver does not support modifying "
14054
                             "<metadata> element"));
14055 14056 14057
            goto cleanup;
            break;
        default:
14058 14059
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("unknown metadata type"));
14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079
            goto cleanup;
            break;
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        switch ((virDomainMetadataType) type) {
        case VIR_DOMAIN_METADATA_DESCRIPTION:
            VIR_FREE(persistentDef->description);
            if (metadata &&
                !(persistentDef->description = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_TITLE:
            VIR_FREE(persistentDef->title);
            if (metadata &&
                !(persistentDef->title = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_ELEMENT:
14080
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
14081
                           _("QEMU driver does not support "
14082
                             "<metadata> element"));
14083 14084
            goto cleanup;
         default:
14085 14086
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("unknown metadata type"));
14087 14088 14089 14090
            goto cleanup;
            break;
        }

14091
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
14092 14093 14094 14095 14096 14097 14098
            goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
14099
        virObjectUnlock(vm);
14100
    virObjectUnref(cfg);
14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112
    return ret;
no_memory:
    virReportOOMError();
    goto cleanup;
}

static char *
qemuDomainGetMetadata(virDomainPtr dom,
                      int type,
                      const char *uri ATTRIBUTE_UNUSED,
                      unsigned int flags)
{
14113
    virQEMUDriverPtr driver = dom->conn->privateData;
14114 14115 14116 14117 14118 14119 14120 14121
    virDomainObjPtr vm;
    virDomainDefPtr def;
    char *ret = NULL;
    char *field = NULL;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, NULL);

14122
    if (!(vm = qemuDomObjFromDomain(dom)))
14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139
        goto cleanup;

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags, &def) < 0)
        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:
14140
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
14141
                       _("QEMU driver does not support "
14142
                         "<metadata> element"));
14143 14144 14145
        goto cleanup;
        break;
    default:
14146 14147
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("unknown metadata type"));
14148 14149 14150 14151 14152
        goto cleanup;
        break;
    }

    if (!field) {
14153 14154
        virReportError(VIR_ERR_NO_DOMAIN_METADATA, "%s",
                       _("Requested metadata element is not present"));
14155 14156 14157 14158 14159 14160 14161 14162 14163 14164
        goto cleanup;
    }

    if (!(ret = strdup(field))) {
        virReportOOMError();
        goto cleanup;
    }

cleanup:
    if (vm)
14165
        virObjectUnlock(vm);
14166 14167 14168
    return ret;
}

14169 14170 14171 14172 14173 14174 14175 14176 14177 14178
/* qemuDomainGetCPUStats() with start_cpu == -1 */
static int
qemuDomainGetTotalcpuStats(virCgroupPtr group,
                           virTypedParameterPtr params,
                           int nparams)
{
    unsigned long long cpu_time;
    int ret;

    if (nparams == 0) /* return supported number of params */
E
Eric Blake 已提交
14179
        return QEMU_NB_TOTAL_CPU_STAT_PARAM;
14180 14181 14182 14183 14184 14185 14186
    /* entry 0 is cputime */
    ret = virCgroupGetCpuacctUsage(group, &cpu_time);
    if (ret < 0) {
        virReportSystemError(-ret, "%s", _("unable to get cpu account"));
        return -1;
    }

E
Eric Blake 已提交
14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215
    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;

        ret = virCgroupGetCpuacctStat(group, &user, &sys);
        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;
14216 14217
}

14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248
/* 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
getSumVcpuPercpuStats(virCgroupPtr group,
                      unsigned int nvcpu,
                      unsigned long long *sum_cpu_time,
                      unsigned int num)
{
    int ret = -1;
    int i;
    char *buf = NULL;
    virCgroupPtr group_vcpu = NULL;

    for (i = 0; i < nvcpu; i++) {
        char *pos;
        unsigned long long tmp;
        int j;

        if (virCgroupForVcpu(group, i, &group_vcpu, 0) < 0) {
14249 14250
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("error accessing cgroup cpuacct for vcpu"));
14251 14252 14253
            goto cleanup;
        }

14254
        if (virCgroupGetCpuacctPercpuUsage(group_vcpu, &buf) < 0)
14255 14256 14257 14258 14259
            goto cleanup;

        pos = buf;
        for (j = 0; j < num; j++) {
            if (virStrToLong_ull(pos, &pos, 10, &tmp) < 0) {
14260 14261
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cpuacct parse error"));
14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277
                goto cleanup;
            }
            sum_cpu_time[j] += tmp;
        }

        virCgroupFree(&group_vcpu);
        VIR_FREE(buf);
    }

    ret = 0;
cleanup:
    virCgroupFree(&group_vcpu);
    VIR_FREE(buf);
    return ret;
}

14278
static int
14279
qemuDomainGetPercpuStats(virDomainObjPtr vm,
14280 14281 14282 14283 14284 14285 14286
                         virCgroupPtr group,
                         virTypedParameterPtr params,
                         unsigned int nparams,
                         int start_cpu,
                         unsigned int ncpus)
{
    int rv = -1;
14287
    int i, id, max_id;
14288 14289
    char *pos;
    char *buf = NULL;
14290 14291 14292 14293
    unsigned long long *sum_cpu_time = NULL;
    unsigned long long *sum_cpu_pos;
    unsigned int n = 0;
    qemuDomainObjPrivatePtr priv = vm->privateData;
14294 14295
    virTypedParameterPtr ent;
    int param_idx;
14296
    unsigned long long cpu_time;
14297 14298 14299

    /* return the number of supported params */
    if (nparams == 0 && ncpus != 0)
14300
        return QEMU_NB_PER_CPU_STAT_PARAM;
14301

14302 14303 14304
    /* To parse account file, we need to know how many cpus are present.  */
    max_id = nodeGetCPUCount();
    if (max_id < 0)
14305 14306 14307
        return rv;

    if (ncpus == 0) { /* returns max cpu ID */
14308
        rv = max_id;
14309 14310 14311 14312
        goto cleanup;
    }

    if (start_cpu > max_id) {
14313 14314 14315
        virReportError(VIR_ERR_INVALID_ARG,
                       _("start_cpu %d larger than maximum of %d"),
                       start_cpu, max_id);
14316 14317 14318 14319 14320 14321 14322
        goto cleanup;
    }

    /* we get percpu cputime accounting info. */
    if (virCgroupGetCpuacctPercpuUsage(group, &buf))
        goto cleanup;
    pos = buf;
14323
    memset(params, 0, nparams * ncpus);
14324

14325 14326 14327
    /* return percpu cputime in index 0 */
    param_idx = 0;

14328 14329 14330
    /* number of cpus to compute */
    id = max_id;

14331
    if (max_id - start_cpu > ncpus - 1)
14332
        id = start_cpu + ncpus - 1;
14333

14334
    for (i = 0; i <= id; i++) {
14335
        if (virStrToLong_ull(pos, &pos, 10, &cpu_time) < 0) {
14336
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
14337
                           _("cpuacct parse error"));
14338
            goto cleanup;
14339 14340
        } else {
            n++;
14341 14342 14343
        }
        if (i < start_cpu)
            continue;
14344
        ent = &params[(i - start_cpu) * nparams + param_idx];
E
Eric Blake 已提交
14345 14346 14347
        if (virTypedParameterAssign(ent, VIR_DOMAIN_CPU_STATS_CPUTIME,
                                    VIR_TYPED_PARAM_ULLONG, cpu_time) < 0)
            goto cleanup;
14348
    }
14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363

    /* 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;
    }
    if (getSumVcpuPercpuStats(group, priv->nvcpupids, sum_cpu_time, n) < 0)
        goto cleanup;

    sum_cpu_pos = sum_cpu_time;
14364
    for (i = 0; i <= id; i++) {
14365
        cpu_time = *(sum_cpu_pos++);
14366 14367 14368 14369 14370 14371 14372 14373 14374 14375
        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;
    }

14376 14377
    rv = param_idx + 1;
cleanup:
14378
    VIR_FREE(sum_cpu_time);
14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391
    VIR_FREE(buf);
    return rv;
}


static int
qemuDomainGetCPUStats(virDomainPtr domain,
                virTypedParameterPtr params,
                unsigned int nparams,
                int start_cpu,
                unsigned int ncpus,
                unsigned int flags)
{
14392
    virQEMUDriverPtr driver = domain->conn->privateData;
14393 14394 14395 14396 14397 14398 14399 14400 14401
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    bool isActive;

    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    qemuDriverLock(driver);

14402
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
14403
    if (vm == NULL) {
14404 14405
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), domain->uuid);
14406 14407 14408 14409 14410
        goto cleanup;
    }

    isActive = virDomainObjIsActive(vm);
    if (!isActive) {
14411 14412
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
14413 14414 14415 14416
        goto cleanup;
    }

    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUACCT)) {
14417 14418
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cgroup CPUACCT controller is not mounted"));
14419 14420 14421 14422
        goto cleanup;
    }

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
14423 14424
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find cgroup for domain %s"), vm->def->name);
14425 14426 14427 14428 14429 14430
        goto cleanup;
    }

    if (start_cpu == -1)
        ret = qemuDomainGetTotalcpuStats(group, params, nparams);
    else
14431
        ret = qemuDomainGetPercpuStats(vm, group, params, nparams,
14432 14433 14434 14435
                                       start_cpu, ncpus);
cleanup:
    virCgroupFree(&group);
    if (vm)
14436
        virObjectUnlock(vm);
14437 14438 14439 14440
    qemuDriverUnlock(driver);
    return ret;
}

14441 14442 14443 14444 14445 14446
static int
qemuDomainPMSuspendForDuration(virDomainPtr dom,
                               unsigned int target,
                               unsigned long long duration,
                               unsigned int flags)
{
14447
    virQEMUDriverPtr driver = dom->conn->privateData;
14448 14449 14450 14451 14452 14453 14454
    qemuDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

    if (duration) {
14455 14456
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("Duration not supported. Use 0 for now"));
14457 14458 14459 14460 14461 14462
        return -1;
    }

    if (!(target == VIR_NODE_SUSPEND_TARGET_MEM ||
          target == VIR_NODE_SUSPEND_TARGET_DISK ||
          target == VIR_NODE_SUSPEND_TARGET_HYBRID)) {
14463 14464 14465
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unknown suspend target: %u"),
                       target);
14466 14467 14468
        return -1;
    }

14469
    if (!(vm = qemuDomObjFromDomain(dom)))
14470 14471 14472 14473
        goto cleanup;

    priv = vm->privateData;

14474
    if (!virDomainObjIsActive(vm)) {
14475 14476
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
14477 14478 14479
        goto cleanup;
    }

14480
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_WAKEUP) &&
14481 14482
        (target == VIR_NODE_SUSPEND_TARGET_MEM ||
         target == VIR_NODE_SUSPEND_TARGET_HYBRID)) {
14483 14484 14485
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("Unable to suspend domain due to "
                         "missing system_wakeup monitor command"));
O
Osier Yang 已提交
14486
        goto cleanup;
14487 14488
    }

14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505
    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;
        }
    }

14506
    if (priv->agentError) {
14507 14508 14509
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("QEMU guest agent is not "
                         "available due to an error"));
14510 14511 14512 14513
        goto cleanup;
    }

    if (!priv->agent) {
14514 14515
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("QEMU guest agent is not configured"));
14516 14517 14518 14519 14520 14521 14522
        goto cleanup;
    }

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

    if (!virDomainObjIsActive(vm)) {
14523 14524
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537
        goto endjob;
    }

    qemuDomainObjEnterAgent(driver, vm);
    ret = qemuAgentSuspend(priv->agent, target);
    qemuDomainObjExitAgent(driver, vm);

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

cleanup:
    if (vm)
14538
        virObjectUnlock(vm);
14539 14540 14541
    return ret;
}

14542 14543 14544 14545
static int
qemuDomainPMWakeup(virDomainPtr dom,
                   unsigned int flags)
{
14546
    virQEMUDriverPtr driver = dom->conn->privateData;
14547 14548 14549 14550 14551 14552
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

14553
    if (!(vm = qemuDomObjFromDomain(dom)))
14554 14555 14556 14557 14558 14559
        goto cleanup;

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

    if (!virDomainObjIsActive(vm)) {
14560 14561
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
14562 14563 14564 14565 14566
        goto endjob;
    }

    priv = vm->privateData;

14567
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_WAKEUP)) {
14568 14569 14570
       virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                      _("Unable to wake up domain due to "
                        "missing system_wakeup monitor command"));
14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583
       goto endjob;
    }

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

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

cleanup:
    if (vm)
14584
        virObjectUnlock(vm);
14585 14586 14587
    return ret;
}

14588 14589 14590 14591 14592
static int
qemuListAllDomains(virConnectPtr conn,
                   virDomainPtr **domains,
                   unsigned int flags)
{
14593
    virQEMUDriverPtr driver = conn->privateData;
14594 14595
    int ret = -1;

O
Osier Yang 已提交
14596
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
14597 14598

    qemuDriverLock(driver);
14599
    ret = virDomainObjListExport(driver->domains, conn, domains, flags);
14600 14601 14602 14603 14604
    qemuDriverUnlock(driver);

    return ret;
}

M
MATSUDA Daiki 已提交
14605
static char *
14606
qemuDomainAgentCommand(virDomainPtr domain,
M
MATSUDA Daiki 已提交
14607 14608 14609 14610
                       const char *cmd,
                       int timeout,
                       unsigned int flags)
{
14611
    virQEMUDriverPtr driver = domain->conn->privateData;
M
MATSUDA Daiki 已提交
14612 14613 14614 14615 14616 14617 14618
    virDomainObjPtr vm;
    int ret = -1;
    char *result = NULL;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, NULL);

14619
    if (!(vm = qemuDomObjFromDomain(domain)))
M
MATSUDA Daiki 已提交
14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630
        goto cleanup;

    priv = vm->privateData;

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

    if (priv->agentError) {
14631 14632 14633
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("QEMU guest agent is not "
                         "available due to an error"));
M
MATSUDA Daiki 已提交
14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667
        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;
    }

    qemuDomainObjEnterAgent(driver, vm);
    ret = qemuAgentArbitraryCommand(priv->agent, cmd, &result, timeout);
    qemuDomainObjExitAgent(driver, vm);
    if (ret < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to execute agent command"));
        goto endjob;
    }

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

cleanup:
    if (vm)
14668
        virObjectUnlock(vm);
M
MATSUDA Daiki 已提交
14669 14670 14671
    return result;
}

M
Michal Privoznik 已提交
14672 14673 14674 14675 14676 14677
static int
qemuDomainFSTrim(virDomainPtr dom,
                 const char *mountPoint,
                 unsigned long long minimum,
                 unsigned int flags)
{
14678
    virQEMUDriverPtr driver = dom->conn->privateData;
M
Michal Privoznik 已提交
14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734
    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;

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

    qemuDomainObjEnterAgent(driver, vm);
    ret = qemuAgentFSTrim(priv->agent, minimum);
    qemuDomainObjExitAgent(driver, vm);

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

cleanup:
    if (vm)
14735
        virObjectUnlock(vm);
M
Michal Privoznik 已提交
14736 14737 14738
    return ret;
}

14739
static virDriver qemuDriver = {
14740
    .no = VIR_DRV_QEMU,
14741
    .name = QEMU_DRIVER_NAME,
14742 14743 14744 14745 14746
    .open = qemuOpen, /* 0.2.0 */
    .close = qemuClose, /* 0.2.0 */
    .supports_feature = qemuSupportsFeature, /* 0.5.0 */
    .type = qemuGetType, /* 0.2.0 */
    .version = qemuGetVersion, /* 0.2.0 */
14747 14748
    .getHostname = virGetHostname, /* 0.3.3 */
    .getSysinfo = qemuGetSysinfo, /* 0.8.8 */
14749
    .getMaxVcpus = qemuGetMaxVCPUs, /* 0.2.1 */
14750
    .nodeGetInfo = nodeGetInfo, /* 0.2.0 */
14751 14752 14753
    .getCapabilities = qemuGetCapabilities, /* 0.2.1 */
    .listDomains = qemuListDomains, /* 0.2.0 */
    .numOfDomains = qemuNumDomains, /* 0.2.0 */
14754
    .listAllDomains = qemuListAllDomains, /* 0.9.13 */
14755 14756 14757 14758 14759 14760
    .domainCreateXML = qemuDomainCreate, /* 0.2.0 */
    .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 */
14761
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
14762
    .domainShutdownFlags = qemuDomainShutdownFlags, /* 0.9.10 */
14763
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
14764
    .domainReset = qemuDomainReset, /* 0.9.7 */
14765 14766
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
14767
    .domainGetOSType = qemuDomainGetOSType, /* 0.2.2 */
14768
    .domainGetMaxMemory = qemuDomainGetMaxMemory, /* 0.4.2 */
14769 14770 14771
    .domainSetMaxMemory = qemuDomainSetMaxMemory, /* 0.4.2 */
    .domainSetMemory = qemuDomainSetMemory, /* 0.4.2 */
    .domainSetMemoryFlags = qemuDomainSetMemoryFlags, /* 0.9.0 */
14772 14773 14774 14775
    .domainSetMemoryParameters = qemuDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = qemuDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = qemuDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = qemuDomainGetBlkioParameters, /* 0.9.0 */
14776
    .domainGetInfo = qemuDomainGetInfo, /* 0.2.0 */
14777
    .domainGetState = qemuDomainGetState, /* 0.9.2 */
14778
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
14779 14780
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
14781
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
14782
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
14783 14784
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
14785
    .domainCoreDump = qemuDomainCoreDump, /* 0.7.0 */
14786
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
14787 14788
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
14789 14790 14791 14792 14793 14794 14795 14796 14797
    .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 已提交
14798
    .domainGetSecurityLabelList = qemuDomainGetSecurityLabelList, /* 0.10.0 */
14799
    .nodeGetSecurityModel = qemuNodeGetSecurityModel, /* 0.6.1 */
14800 14801 14802
    .domainGetXMLDesc = qemuDomainGetXMLDesc, /* 0.2.0 */
    .domainXMLFromNative = qemuDomainXMLFromNative, /* 0.6.4 */
    .domainXMLToNative = qemuDomainXMLToNative, /* 0.6.4 */
14803 14804
    .listDefinedDomains = qemuListDefinedDomains, /* 0.2.0 */
    .numOfDefinedDomains = qemuNumDefinedDomains, /* 0.2.0 */
14805 14806
    .domainCreate = qemuDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainStartWithFlags, /* 0.8.2 */
14807 14808
    .domainDefineXML = qemuDomainDefine, /* 0.2.0 */
    .domainUndefine = qemuDomainUndefine, /* 0.2.0 */
14809
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
14810 14811 14812 14813 14814
    .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 */
14815 14816
    .domainGetAutostart = qemuDomainGetAutostart, /* 0.2.1 */
    .domainSetAutostart = qemuDomainSetAutostart, /* 0.2.1 */
14817 14818
    .domainGetSchedulerType = qemuGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = qemuGetSchedulerParameters, /* 0.7.0 */
14819
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
14820
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
14821
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
14822
    .domainMigratePerform = qemuDomainMigratePerform, /* 0.5.0 */
14823
    .domainBlockResize = qemuDomainBlockResize, /* 0.9.8 */
14824 14825
    .domainBlockStats = qemuDomainBlockStats, /* 0.4.1 */
    .domainBlockStatsFlags = qemuDomainBlockStatsFlags, /* 0.9.5 */
14826 14827 14828 14829
    .domainInterfaceStats = qemuDomainInterfaceStats, /* 0.4.1 */
    .domainMemoryStats = qemuDomainMemoryStats, /* 0.7.5 */
    .domainBlockPeek = qemuDomainBlockPeek, /* 0.4.4 */
    .domainMemoryPeek = qemuDomainMemoryPeek, /* 0.4.4 */
14830
    .domainGetBlockInfo = qemuDomainGetBlockInfo, /* 0.8.1 */
14831
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
14832
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
14833 14834 14835 14836
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.4.4 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.4.4 */
    .domainEventRegister = qemuDomainEventRegister, /* 0.5.0 */
    .domainEventDeregister = qemuDomainEventDeregister, /* 0.5.0 */
14837 14838 14839 14840 14841 14842
    .domainMigratePrepare2 = qemuDomainMigratePrepare2, /* 0.5.0 */
    .domainMigrateFinish2 = qemuDomainMigrateFinish2, /* 0.5.0 */
    .nodeDeviceDettach = qemuNodeDeviceDettach, /* 0.6.1 */
    .nodeDeviceReAttach = qemuNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = qemuNodeDeviceReset, /* 0.6.1 */
    .domainMigratePrepareTunnel = qemuDomainMigratePrepareTunnel, /* 0.7.2 */
14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853
    .isEncrypted = qemuIsEncrypted, /* 0.7.3 */
    .isSecure = qemuIsSecure, /* 0.7.3 */
    .domainIsActive = qemuDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = qemuDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = qemuDomainIsUpdated, /* 0.8.6 */
    .cpuCompare = qemuCPUCompare, /* 0.7.5 */
    .cpuBaseline = qemuCPUBaseline, /* 0.7.7 */
    .domainGetJobInfo = qemuDomainGetJobInfo, /* 0.7.7 */
    .domainAbortJob = qemuDomainAbortJob, /* 0.7.7 */
    .domainMigrateSetMaxDowntime = qemuDomainMigrateSetMaxDowntime, /* 0.8.0 */
    .domainMigrateSetMaxSpeed = qemuDomainMigrateSetMaxSpeed, /* 0.9.0 */
14854
    .domainMigrateGetMaxSpeed = qemuDomainMigrateGetMaxSpeed, /* 0.9.5 */
14855 14856 14857 14858 14859 14860 14861 14862 14863
    .domainEventRegisterAny = qemuDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = qemuDomainEventDeregisterAny, /* 0.8.0 */
    .domainManagedSave = qemuDomainManagedSave, /* 0.8.0 */
    .domainHasManagedSaveImage = qemuDomainHasManagedSaveImage, /* 0.8.0 */
    .domainManagedSaveRemove = qemuDomainManagedSaveRemove, /* 0.8.0 */
    .domainSnapshotCreateXML = qemuDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = qemuDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = qemuDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = qemuDomainSnapshotListNames, /* 0.8.0 */
14864
    .domainListAllSnapshots = qemuDomainListAllSnapshots, /* 0.9.13 */
14865 14866
    .domainSnapshotNumChildren = qemuDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = qemuDomainSnapshotListChildrenNames, /* 0.9.7 */
14867
    .domainSnapshotListAllChildren = qemuDomainSnapshotListAllChildren, /* 0.9.13 */
14868 14869
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
14870
    .domainSnapshotGetParent = qemuDomainSnapshotGetParent, /* 0.9.7 */
14871
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
14872 14873
    .domainSnapshotIsCurrent = qemuDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = qemuDomainSnapshotHasMetadata, /* 0.9.13 */
14874 14875 14876
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
14877
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
14878
    .qemuDomainArbitraryAgentCommand = qemuDomainAgentCommand, /* 0.10.0 */
14879
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
14880
    .domainOpenGraphics = qemuDomainOpenGraphics, /* 0.9.7 */
14881
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
14882 14883 14884 14885 14886 14887
    .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 */
14888
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
14889 14890 14891 14892
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
14893
    .domainBlockRebase = qemuDomainBlockRebase, /* 0.9.10 */
14894
    .domainBlockCommit = qemuDomainBlockCommit, /* 1.0.0 */
14895
    .isAlive = qemuIsAlive, /* 0.9.8 */
14896
    .nodeSuspendForDuration = nodeSuspendForDuration, /* 0.9.8 */
14897 14898
    .domainSetBlockIoTune = qemuDomainSetBlockIoTune, /* 0.9.8 */
    .domainGetBlockIoTune = qemuDomainGetBlockIoTune, /* 0.9.8 */
14899 14900
    .domainSetNumaParameters = qemuDomainSetNumaParameters, /* 0.9.9 */
    .domainGetNumaParameters = qemuDomainGetNumaParameters, /* 0.9.9 */
14901 14902
    .domainGetInterfaceParameters = qemuDomainGetInterfaceParameters, /* 0.9.9 */
    .domainSetInterfaceParameters = qemuDomainSetInterfaceParameters, /* 0.9.9 */
14903
    .domainGetDiskErrors = qemuDomainGetDiskErrors, /* 0.9.10 */
14904 14905
    .domainSetMetadata = qemuDomainSetMetadata, /* 0.9.10 */
    .domainGetMetadata = qemuDomainGetMetadata, /* 0.9.10 */
14906
    .domainPMSuspendForDuration = qemuDomainPMSuspendForDuration, /* 0.9.11 */
14907
    .domainPMWakeup = qemuDomainPMWakeup, /* 0.9.11 */
14908
    .domainGetCPUStats = qemuDomainGetCPUStats, /* 0.9.11 */
14909 14910
    .nodeGetMemoryParameters = nodeGetMemoryParameters, /* 0.10.2 */
    .nodeSetMemoryParameters = nodeSetMemoryParameters, /* 0.10.2 */
14911
    .nodeGetCPUMap = nodeGetCPUMap, /* 1.0.0 */
M
Michal Privoznik 已提交
14912
    .domainFSTrim = qemuDomainFSTrim, /* 1.0.1 */
14913
    .domainOpenChannel = qemuDomainOpenChannel, /* 1.0.2 */
14914 14915 14916
};


14917
static virStateDriver qemuStateDriver = {
14918
    .name = "QEMU",
14919 14920 14921
    .initialize = qemuStartup,
    .cleanup = qemuShutdown,
    .reload = qemuReload,
14922
    .stop = qemuStop,
14923
};
14924

14925
int qemuRegister(void) {
14926 14927 14928 14929
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}