qemu_domain.c 90.6 KB
Newer Older
1
/*
2
 * qemu_domain.c: QEMU domain private state
3
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
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/>.
20 21 22 23 24 25 26 27
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include "qemu_domain.h"
#include "qemu_command.h"
28
#include "qemu_capabilities.h"
29
#include "qemu_migration.h"
30
#include "viralloc.h"
31
#include "virlog.h"
32
#include "virerror.h"
33
#include "c-ctype.h"
34
#include "cpu/cpu.h"
35
#include "viruuid.h"
E
Eric Blake 已提交
36
#include "virfile.h"
37
#include "domain_addr.h"
38
#include "domain_event.h"
39
#include "virtime.h"
40
#include "virstoragefile.h"
41
#include "virstring.h"
42
#include "virthreadjob.h"
43

44 45
#include "storage/storage_driver.h"

46
#include <sys/time.h>
47
#include <fcntl.h>
48

49 50 51 52
#include <libxml/xpathInternals.h>

#define VIR_FROM_THIS VIR_FROM_QEMU

53 54
VIR_LOG_INIT("qemu.qemu_domain");

55 56
#define QEMU_NAMESPACE_HREF "http://libvirt.org/schemas/domain/qemu/1.0"

57 58 59 60 61 62
VIR_ENUM_IMPL(qemuDomainJob, QEMU_JOB_LAST,
              "none",
              "query",
              "destroy",
              "suspend",
              "modify",
63
              "abort",
64
              "migration operation",
65 66 67 68 69 70 71 72 73 74
              "none",   /* async job is never stored in job.active */
              "async nested",
);

VIR_ENUM_IMPL(qemuDomainAsyncJob, QEMU_ASYNC_JOB_LAST,
              "none",
              "migration out",
              "migration in",
              "save",
              "dump",
75
              "snapshot",
76 77
);

78

J
Jiri Denemark 已提交
79
const char *
80
qemuDomainAsyncJobPhaseToString(qemuDomainAsyncJob job,
J
Jiri Denemark 已提交
81 82 83 84 85
                                int phase ATTRIBUTE_UNUSED)
{
    switch (job) {
    case QEMU_ASYNC_JOB_MIGRATION_OUT:
    case QEMU_ASYNC_JOB_MIGRATION_IN:
86 87
        return qemuMigrationJobPhaseTypeToString(phase);

J
Jiri Denemark 已提交
88 89
    case QEMU_ASYNC_JOB_SAVE:
    case QEMU_ASYNC_JOB_DUMP:
90
    case QEMU_ASYNC_JOB_SNAPSHOT:
J
Jiri Denemark 已提交
91 92 93 94 95 96 97 98 99
    case QEMU_ASYNC_JOB_NONE:
    case QEMU_ASYNC_JOB_LAST:
        ; /* fall through */
    }

    return "none";
}

int
100
qemuDomainAsyncJobPhaseFromString(qemuDomainAsyncJob job,
J
Jiri Denemark 已提交
101 102 103 104 105 106 107 108
                                  const char *phase)
{
    if (!phase)
        return 0;

    switch (job) {
    case QEMU_ASYNC_JOB_MIGRATION_OUT:
    case QEMU_ASYNC_JOB_MIGRATION_IN:
109 110
        return qemuMigrationJobPhaseTypeFromString(phase);

J
Jiri Denemark 已提交
111 112
    case QEMU_ASYNC_JOB_SAVE:
    case QEMU_ASYNC_JOB_DUMP:
113
    case QEMU_ASYNC_JOB_SNAPSHOT:
J
Jiri Denemark 已提交
114 115 116 117 118 119 120 121 122 123 124
    case QEMU_ASYNC_JOB_NONE:
    case QEMU_ASYNC_JOB_LAST:
        ; /* fall through */
    }

    if (STREQ(phase, "none"))
        return 0;
    else
        return -1;
}

125

126
void qemuDomainEventQueue(virQEMUDriverPtr driver,
127
                          virObjectEventPtr event)
128
{
129
    virObjectEventStateQueue(driver->domainEventState, event);
130 131 132
}


133 134 135 136 137 138 139 140
static int
qemuDomainObjInitJob(qemuDomainObjPrivatePtr priv)
{
    memset(&priv->job, 0, sizeof(priv->job));

    if (virCondInit(&priv->job.cond) < 0)
        return -1;

141
    if (virCondInit(&priv->job.asyncCond) < 0) {
142
        virCondDestroy(&priv->job.cond);
143 144 145
        return -1;
    }

146 147 148 149 150 151 152 153 154
    return 0;
}

static void
qemuDomainObjResetJob(qemuDomainObjPrivatePtr priv)
{
    struct qemuDomainJobObj *job = &priv->job;

    job->active = QEMU_JOB_NONE;
155
    job->owner = 0;
156
    job->ownerAPI = NULL;
J
Jiri Denemark 已提交
157
    job->started = 0;
158 159 160 161 162 163 164 165
}

static void
qemuDomainObjResetAsyncJob(qemuDomainObjPrivatePtr priv)
{
    struct qemuDomainJobObj *job = &priv->job;

    job->asyncJob = QEMU_ASYNC_JOB_NONE;
166
    job->asyncOwner = 0;
167
    job->asyncOwnerAPI = NULL;
J
Jiri Denemark 已提交
168
    job->asyncStarted = 0;
J
Jiri Denemark 已提交
169
    job->phase = 0;
170
    job->mask = QEMU_JOB_DEFAULT_MASK;
171
    job->dump_memory_only = false;
172
    job->asyncAbort = false;
J
Jiri Denemark 已提交
173
    VIR_FREE(job->current);
174 175
}

176 177 178 179 180 181 182 183
void
qemuDomainObjRestoreJob(virDomainObjPtr obj,
                        struct qemuDomainJobObj *job)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    memset(job, 0, sizeof(*job));
    job->active = priv->job.active;
184
    job->owner = priv->job.owner;
185
    job->asyncJob = priv->job.asyncJob;
186
    job->asyncOwner = priv->job.asyncOwner;
J
Jiri Denemark 已提交
187
    job->phase = priv->job.phase;
188 189 190 191 192

    qemuDomainObjResetJob(priv);
    qemuDomainObjResetAsyncJob(priv);
}

193 194 195
static void
qemuDomainObjFreeJob(qemuDomainObjPrivatePtr priv)
{
J
Jiri Denemark 已提交
196
    VIR_FREE(priv->job.current);
197
    VIR_FREE(priv->job.completed);
198 199
    virCondDestroy(&priv->job.cond);
    virCondDestroy(&priv->job.asyncCond);
200 201
}

202
static bool
203
qemuDomainTrackJob(qemuDomainJob job)
204 205 206 207
{
    return (QEMU_DOMAIN_TRACK_JOBS & JOB_MASK(job)) != 0;
}

208

J
Jiri Denemark 已提交
209 210 211 212 213 214 215 216 217 218 219
int
qemuDomainJobInfoUpdateTime(qemuDomainJobInfoPtr jobInfo)
{
    unsigned long long now;

    if (!jobInfo->started)
        return 0;

    if (virTimeMillisNow(&now) < 0)
        return -1;

220 221 222 223 224 225
    if (now < jobInfo->started) {
        VIR_WARN("Async job starts in the future");
        jobInfo->started = 0;
        return 0;
    }

J
Jiri Denemark 已提交
226 227 228 229
    jobInfo->timeElapsed = now - jobInfo->started;
    return 0;
}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
int
qemuDomainJobInfoUpdateDowntime(qemuDomainJobInfoPtr jobInfo)
{
    unsigned long long now;

    if (!jobInfo->stopped)
        return 0;

    if (virTimeMillisNow(&now) < 0)
        return -1;

    if (now < jobInfo->stopped) {
        VIR_WARN("Guest's CPUs stopped in the future");
        jobInfo->stopped = 0;
        return 0;
    }

    jobInfo->status.downtime = now - jobInfo->stopped;
    jobInfo->status.downtime_set = true;
    return 0;
}

J
Jiri Denemark 已提交
252 253 254 255
int
qemuDomainJobInfoToInfo(qemuDomainJobInfoPtr jobInfo,
                        virDomainJobInfoPtr info)
{
256
    info->type = jobInfo->type;
J
Jiri Denemark 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    info->timeElapsed = jobInfo->timeElapsed;
    info->timeRemaining = jobInfo->timeRemaining;

    info->memTotal = jobInfo->status.ram_total;
    info->memRemaining = jobInfo->status.ram_remaining;
    info->memProcessed = jobInfo->status.ram_transferred;

    info->fileTotal = jobInfo->status.disk_total;
    info->fileRemaining = jobInfo->status.disk_remaining;
    info->fileProcessed = jobInfo->status.disk_transferred;

    info->dataTotal = info->memTotal + info->fileTotal;
    info->dataRemaining = info->memRemaining + info->fileRemaining;
    info->dataProcessed = info->memProcessed + info->fileProcessed;

    return 0;
}

int
qemuDomainJobInfoToParams(qemuDomainJobInfoPtr jobInfo,
                          int *type,
                          virTypedParameterPtr *params,
                          int *nparams)
{
    qemuMonitorMigrationStatus *status = &jobInfo->status;
    virTypedParameterPtr par = NULL;
    int maxpar = 0;
    int npar = 0;

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_TIME_ELAPSED,
                                jobInfo->timeElapsed) < 0)
        goto error;

    if (jobInfo->type == VIR_DOMAIN_JOB_BOUNDED &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_TIME_REMAINING,
                                jobInfo->timeRemaining) < 0)
        goto error;

    if (status->downtime_set &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DOWNTIME,
                                status->downtime) < 0)
        goto error;

303 304 305 306 307 308
    if (status->setup_time_set &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_SETUP_TIME,
                                status->setup_time) < 0)
        goto error;

J
Jiri Denemark 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_TOTAL,
                                status->ram_total +
                                status->disk_total) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_PROCESSED,
                                status->ram_transferred +
                                status->disk_transferred) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_REMAINING,
                                status->ram_remaining +
                                status->disk_remaining) < 0)
        goto error;

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_TOTAL,
                                status->ram_total) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_PROCESSED,
                                status->ram_transferred) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_REMAINING,
                                status->ram_remaining) < 0)
        goto error;

334 335 336 337 338 339
    if (status->ram_bps &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_BPS,
                                status->ram_bps) < 0)
        goto error;

J
Jiri Denemark 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    if (status->ram_duplicate_set) {
        if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_CONSTANT,
                                    status->ram_duplicate) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_NORMAL,
                                    status->ram_normal) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES,
                                    status->ram_normal_bytes) < 0)
            goto error;
    }

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_TOTAL,
                                status->disk_total) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_PROCESSED,
                                status->disk_transferred) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_REMAINING,
                                status->disk_remaining) < 0)
        goto error;

364 365 366 367 368 369
    if (status->disk_bps &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_BPS,
                                status->disk_bps) < 0)
        goto error;

J
Jiri Denemark 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    if (status->xbzrle_set) {
        if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_CACHE,
                                    status->xbzrle_cache_size) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_BYTES,
                                    status->xbzrle_bytes) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_PAGES,
                                    status->xbzrle_pages) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_CACHE_MISSES,
                                    status->xbzrle_cache_miss) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_OVERFLOW,
                                    status->xbzrle_overflow) < 0)
            goto error;
    }

    *type = jobInfo->type;
    *params = par;
    *nparams = npar;
    return 0;

 error:
    virTypedParamsFree(par, npar);
    return -1;
}


400 401
static void *
qemuDomainObjPrivateAlloc(void)
402 403 404 405 406 407
{
    qemuDomainObjPrivatePtr priv;

    if (VIR_ALLOC(priv) < 0)
        return NULL;

408 409 410
    if (qemuDomainObjInitJob(priv) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to init qemu driver mutexes"));
411
        goto error;
412
    }
413

414 415 416
    if (virCondInit(&priv->unplugFinished) < 0)
        goto error;

417
    if (!(priv->devs = virChrdevAlloc()))
418 419
        goto error;

420
    priv->migMaxBandwidth = QEMU_DOMAIN_MIG_BANDWIDTH_MAX;
421

422
    return priv;
423

424
 error:
425 426
    VIR_FREE(priv);
    return NULL;
427 428
}

429 430
static void
qemuDomainObjPrivateFree(void *data)
431 432 433
{
    qemuDomainObjPrivatePtr priv = data;

434
    virObjectUnref(priv->qemuCaps);
435

436
    virCgroupFree(&priv->cgroup);
437
    virDomainPCIAddressSetFree(priv->pciaddrs);
J
Ján Tomko 已提交
438
    virDomainCCWAddressSetFree(priv->ccwaddrs);
439
    virDomainVirtioSerialAddrSetFree(priv->vioserialaddrs);
440
    virDomainChrSourceDefFree(priv->monConfig);
441
    qemuDomainObjFreeJob(priv);
442
    VIR_FREE(priv->vcpupids);
443
    VIR_FREE(priv->iothreadpids);
444
    VIR_FREE(priv->lockState);
J
Jiri Denemark 已提交
445
    VIR_FREE(priv->origname);
446

447
    virCondDestroy(&priv->unplugFinished);
448
    virStringFreeList(priv->qemuDevices);
449
    virChrdevFree(priv->devs);
450

451 452
    /* This should never be non-NULL if we get here, but just in case... */
    if (priv->mon) {
453
        VIR_ERROR(_("Unexpected QEMU monitor still active during domain deletion"));
454 455
        qemuMonitorClose(priv->mon);
    }
D
Daniel P. Berrange 已提交
456 457 458 459
    if (priv->agent) {
        VIR_ERROR(_("Unexpected QEMU agent still active during domain deletion"));
        qemuAgentClose(priv->agent);
    }
460
    VIR_FREE(priv->cleanupCallbacks);
461
    virBitmapFree(priv->autoNodeset);
462
    virBitmapFree(priv->autoCpuset);
463 464 465 466
    VIR_FREE(priv);
}


467 468
static int
qemuDomainObjPrivateXMLFormat(virBufferPtr buf, void *data)
469 470 471
{
    qemuDomainObjPrivatePtr priv = data;
    const char *monitorpath;
472
    qemuDomainJob job;
473 474 475

    /* priv->monitor_chr is set only for qemu */
    if (priv->monConfig) {
476
        switch (priv->monConfig->type) {
477
        case VIR_DOMAIN_CHR_TYPE_UNIX:
478
            monitorpath = priv->monConfig->data.nix.path;
479 480 481
            break;
        default:
        case VIR_DOMAIN_CHR_TYPE_PTY:
482
            monitorpath = priv->monConfig->data.file.path;
483 484 485
            break;
        }

486
        virBufferEscapeString(buf, "<monitor path='%s'", monitorpath);
487 488
        if (priv->monJSON)
            virBufferAddLit(buf, " json='1'");
489
        virBufferAsprintf(buf, " type='%s'/>\n",
490
                          virDomainChrTypeToString(priv->monConfig->type));
491 492 493 494
    }


    if (priv->nvcpupids) {
495
        size_t i;
496 497
        virBufferAddLit(buf, "<vcpus>\n");
        virBufferAdjustIndent(buf, 2);
498
        for (i = 0; i < priv->nvcpupids; i++)
499 500 501
            virBufferAsprintf(buf, "<vcpu pid='%d'/>\n", priv->vcpupids[i]);
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</vcpus>\n");
502 503
    }

504 505 506 507 508 509 510 511 512 513 514 515
    if (priv->niothreadpids) {
        size_t i;
        virBufferAddLit(buf, "<iothreads>\n");
        virBufferAdjustIndent(buf, 2);
        for (i = 0; i < priv->niothreadpids; i++) {
            virBufferAsprintf(buf, "<iothread pid='%d'/>\n",
                              priv->iothreadpids[i]);
        }
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</iothreads>\n");
    }

516
    if (priv->qemuCaps) {
517
        size_t i;
518 519
        virBufferAddLit(buf, "<qemuCaps>\n");
        virBufferAdjustIndent(buf, 2);
520
        for (i = 0; i < QEMU_CAPS_LAST; i++) {
521
            if (virQEMUCapsGet(priv->qemuCaps, i)) {
522
                virBufferAsprintf(buf, "<flag name='%s'/>\n",
523
                                  virQEMUCapsTypeToString(i));
524 525
            }
        }
526 527
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</qemuCaps>\n");
528 529
    }

530
    if (priv->lockState)
531
        virBufferAsprintf(buf, "<lockstate>%s</lockstate>\n", priv->lockState);
532

533 534 535 536
    job = priv->job.active;
    if (!qemuDomainTrackJob(job))
        priv->job.active = QEMU_JOB_NONE;

537
    if (priv->job.active || priv->job.asyncJob) {
538
        virBufferAsprintf(buf, "<job type='%s' async='%s'",
539 540
                          qemuDomainJobTypeToString(priv->job.active),
                          qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
J
Jiri Denemark 已提交
541 542 543 544 545 546
        if (priv->job.phase) {
            virBufferAsprintf(buf, " phase='%s'",
                              qemuDomainAsyncJobPhaseToString(
                                    priv->job.asyncJob, priv->job.phase));
        }
        virBufferAddLit(buf, "/>\n");
547
    }
548
    priv->job.active = job;
549

550
    if (priv->fakeReboot)
551
        virBufferAddLit(buf, "<fakereboot/>\n");
552

553 554
    if (priv->qemuDevices && *priv->qemuDevices) {
        char **tmp = priv->qemuDevices;
555 556
        virBufferAddLit(buf, "<devices>\n");
        virBufferAdjustIndent(buf, 2);
557
        while (*tmp) {
558
            virBufferAsprintf(buf, "<device alias='%s'/>\n", *tmp);
559 560
            tmp++;
        }
561 562
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</devices>\n");
563 564
    }

565 566 567
    return 0;
}

568 569
static int
qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt, void *data)
570 571 572 573
{
    qemuDomainObjPrivatePtr priv = data;
    char *monitorpath;
    char *tmp;
574 575
    int n;
    size_t i;
576
    xmlNodePtr *nodes = NULL;
577
    virQEMUCapsPtr qemuCaps = NULL;
578

579
    if (VIR_ALLOC(priv->monConfig) < 0)
580 581 582 583
        goto error;

    if (!(monitorpath =
          virXPathString("string(./monitor[1]/@path)", ctxt))) {
584 585
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no monitor path"));
586 587 588 589 590
        goto error;
    }

    tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
    if (tmp)
591
        priv->monConfig->type = virDomainChrTypeFromString(tmp);
592
    else
593
        priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
594 595
    VIR_FREE(tmp);

E
Eric Blake 已提交
596 597
    priv->monJSON = virXPathBoolean("count(./monitor[@json = '1']) > 0",
                                    ctxt) > 0;
598

599
    switch (priv->monConfig->type) {
600
    case VIR_DOMAIN_CHR_TYPE_PTY:
601
        priv->monConfig->data.file.path = monitorpath;
602 603
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
604
        priv->monConfig->data.nix.path = monitorpath;
605 606 607
        break;
    default:
        VIR_FREE(monitorpath);
608 609 610
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported monitor type '%s'"),
                       virDomainChrTypeToString(priv->monConfig->type));
611 612 613 614 615 616 617 618
        goto error;
    }

    n = virXPathNodeSet("./vcpus/vcpu", ctxt, &nodes);
    if (n < 0)
        goto error;
    if (n) {
        priv->nvcpupids = n;
619
        if (VIR_REALLOC_N(priv->vcpupids, priv->nvcpupids) < 0)
620 621
            goto error;

622
        for (i = 0; i < n; i++) {
623 624 625 626 627 628 629 630 631 632 633 634
            char *pidstr = virXMLPropString(nodes[i], "pid");
            if (!pidstr)
                goto error;

            if (virStrToLong_i(pidstr, NULL, 10, &(priv->vcpupids[i])) < 0) {
                VIR_FREE(pidstr);
                goto error;
            }
            VIR_FREE(pidstr);
        }
        VIR_FREE(nodes);
    }
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

    n = virXPathNodeSet("./iothreads/iothread", ctxt, &nodes);
    if (n < 0)
        goto error;
    if (n) {
        priv->niothreadpids = n;
        if (VIR_REALLOC_N(priv->iothreadpids, priv->niothreadpids) < 0)
            goto error;

        for (i = 0; i < n; i++) {
            char *pidstr = virXMLPropString(nodes[i], "pid");
            if (!pidstr)
                goto error;

            if (virStrToLong_i(pidstr, NULL, 10,
                               &(priv->iothreadpids[i])) < 0) {
                VIR_FREE(pidstr);
                goto error;
            }
            VIR_FREE(pidstr);
        }
        VIR_FREE(nodes);
    }
658

659
    if ((n = virXPathNodeSet("./qemuCaps/flag", ctxt, &nodes)) < 0) {
660 661
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to parse qemu capabilities flags"));
662 663 664
        goto error;
    }
    if (n > 0) {
665
        if (!(qemuCaps = virQEMUCapsNew()))
666 667
            goto error;

668
        for (i = 0; i < n; i++) {
669 670
            char *str = virXMLPropString(nodes[i], "name");
            if (str) {
671
                int flag = virQEMUCapsTypeFromString(str);
672
                if (flag < 0) {
673 674
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unknown qemu capabilities flag %s"), str);
675
                    VIR_FREE(str);
676 677
                    goto error;
                }
678
                VIR_FREE(str);
679
                virQEMUCapsSet(qemuCaps, flag);
680 681 682
            }
        }

683
        priv->qemuCaps = qemuCaps;
684 685 686
    }
    VIR_FREE(nodes);

687
    priv->lockState = virXPathString("string(./lockstate)", ctxt);
688

689 690 691 692
    if ((tmp = virXPathString("string(./job[1]/@type)", ctxt))) {
        int type;

        if ((type = qemuDomainJobTypeFromString(tmp)) < 0) {
693 694
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown job type %s"), tmp);
695 696 697 698 699 700 701 702 703 704 705
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
        priv->job.active = type;
    }

    if ((tmp = virXPathString("string(./job[1]/@async)", ctxt))) {
        int async;

        if ((async = qemuDomainAsyncJobTypeFromString(tmp)) < 0) {
706 707
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown async job type %s"), tmp);
708 709 710 711 712
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
        priv->job.asyncJob = async;
J
Jiri Denemark 已提交
713 714 715 716

        if ((tmp = virXPathString("string(./job[1]/@phase)", ctxt))) {
            priv->job.phase = qemuDomainAsyncJobPhaseFromString(async, tmp);
            if (priv->job.phase < 0) {
717 718
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unknown job phase %s"), tmp);
J
Jiri Denemark 已提交
719 720 721 722 723
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        }
724 725
    }

726 727
    priv->fakeReboot = virXPathBoolean("boolean(./fakereboot)", ctxt) == 1;

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
    if ((n = virXPathNodeSet("./devices/device", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to parse qemu device list"));
        goto error;
    }
    if (n > 0) {
        /* NULL-terminated list */
        if (VIR_ALLOC_N(priv->qemuDevices, n + 1) < 0)
            goto error;

        for (i = 0; i < n; i++) {
            priv->qemuDevices[i] = virXMLPropString(nodes[i], "alias");
            if (!priv->qemuDevices[i]) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to parse qemu device list"));
                goto error;
            }
        }
    }
    VIR_FREE(nodes);

749 750
    return 0;

751
 error:
752
    virDomainChrSourceDefFree(priv->monConfig);
753 754
    priv->monConfig = NULL;
    VIR_FREE(nodes);
755 756
    virStringFreeList(priv->qemuDevices);
    priv->qemuDevices = NULL;
757
    virObjectUnref(qemuCaps);
758 759 760 761
    return -1;
}


762 763 764 765 766 767 768 769
virDomainXMLPrivateDataCallbacks virQEMUDriverPrivateDataCallbacks = {
    .alloc = qemuDomainObjPrivateAlloc,
    .free = qemuDomainObjPrivateFree,
    .parse = qemuDomainObjPrivateXMLParse,
    .format = qemuDomainObjPrivateXMLFormat,
};


770 771 772 773 774
static void
qemuDomainDefNamespaceFree(void *nsdata)
{
    qemuDomainCmdlineDefPtr cmd = nsdata;

775
    qemuDomainCmdlineDefFree(cmd);
776 777 778
}

static int
P
Philipp Hahn 已提交
779 780
qemuDomainDefNamespaceParse(xmlDocPtr xml ATTRIBUTE_UNUSED,
                            xmlNodePtr root ATTRIBUTE_UNUSED,
781 782 783 784
                            xmlXPathContextPtr ctxt,
                            void **data)
{
    qemuDomainCmdlineDefPtr cmd = NULL;
P
Philipp Hahn 已提交
785
    bool uses_qemu_ns = false;
786
    xmlNodePtr *nodes = NULL;
787 788
    int n;
    size_t i;
789

P
Philipp Hahn 已提交
790
    if (xmlXPathRegisterNs(ctxt, BAD_CAST "qemu", BAD_CAST QEMU_NAMESPACE_HREF) < 0) {
791 792 793
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to register xml namespace '%s'"),
                       QEMU_NAMESPACE_HREF);
794 795 796
        return -1;
    }

797
    if (VIR_ALLOC(cmd) < 0)
798 799 800 801 802 803
        return -1;

    /* first handle the extra command-line arguments */
    n = virXPathNodeSet("./qemu:commandline/qemu:arg", ctxt, &nodes);
    if (n < 0)
        goto error;
P
Philipp Hahn 已提交
804
    uses_qemu_ns |= n > 0;
805 806

    if (n && VIR_ALLOC_N(cmd->args, n) < 0)
807
        goto error;
808 809 810 811

    for (i = 0; i < n; i++) {
        cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
        if (cmd->args[cmd->num_args] == NULL) {
812 813
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu command-line argument specified"));
814 815 816 817 818 819 820 821 822 823 824
            goto error;
        }
        cmd->num_args++;
    }

    VIR_FREE(nodes);

    /* now handle the extra environment variables */
    n = virXPathNodeSet("./qemu:commandline/qemu:env", ctxt, &nodes);
    if (n < 0)
        goto error;
P
Philipp Hahn 已提交
825
    uses_qemu_ns |= n > 0;
826 827

    if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
828
        goto error;
829 830

    if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
831
        goto error;
832 833 834 835 836 837

    for (i = 0; i < n; i++) {
        char *tmp;

        tmp = virXMLPropString(nodes[i], "name");
        if (tmp == NULL) {
838 839
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu environment name specified"));
840 841 842
            goto error;
        }
        if (tmp[0] == '\0') {
843 844
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Empty qemu environment name specified"));
845 846 847
            goto error;
        }
        if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
848 849
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must begin with a letter or underscore"));
850 851 852
            goto error;
        }
        if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
853 854
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
855 856 857 858 859 860 861 862 863 864 865 866
            goto error;
        }

        cmd->env_name[cmd->num_env] = tmp;

        cmd->env_value[cmd->num_env] = virXMLPropString(nodes[i], "value");
        /* a NULL value for command is allowed, since it might be empty */
        cmd->num_env++;
    }

    VIR_FREE(nodes);

P
Philipp Hahn 已提交
867 868 869 870
    if (uses_qemu_ns)
        *data = cmd;
    else
        VIR_FREE(cmd);
871 872 873

    return 0;

874
 error:
875 876 877 878 879 880 881 882 883 884
    VIR_FREE(nodes);
    qemuDomainDefNamespaceFree(cmd);
    return -1;
}

static int
qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
                                void *nsdata)
{
    qemuDomainCmdlineDefPtr cmd = nsdata;
885
    size_t i;
886 887 888 889

    if (!cmd->num_args && !cmd->num_env)
        return 0;

890 891 892
    virBufferAddLit(buf, "<qemu:commandline>\n");
    virBufferAdjustIndent(buf, 2);

893
    for (i = 0; i < cmd->num_args; i++)
894
        virBufferEscapeString(buf, "<qemu:arg value='%s'/>\n",
895 896
                              cmd->args[i]);
    for (i = 0; i < cmd->num_env; i++) {
897
        virBufferAsprintf(buf, "<qemu:env name='%s'", cmd->env_name[i]);
898 899 900 901 902
        if (cmd->env_value[i])
            virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
        virBufferAddLit(buf, "/>\n");
    }

903 904
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</qemu:commandline>\n");
905 906 907 908 909 910 911 912 913 914
    return 0;
}

static const char *
qemuDomainDefNamespaceHref(void)
{
    return "xmlns:qemu='" QEMU_NAMESPACE_HREF "'";
}


915 916 917 918 919 920
virDomainXMLNamespace virQEMUDriverDomainXMLNamespace = {
    .parse = qemuDomainDefNamespaceParse,
    .free = qemuDomainDefNamespaceFree,
    .format = qemuDomainDefNamespaceFormatXML,
    .href = qemuDomainDefNamespaceHref,
};
921

922

923 924 925 926 927
static int
qemuDomainDefPostParse(virDomainDefPtr def,
                       virCapsPtr caps,
                       void *opaque ATTRIBUTE_UNUSED)
{
928
    bool addDefaultUSB = true;
929
    bool addImplicitSATA = false;
930
    bool addPCIRoot = false;
L
Laine Stump 已提交
931
    bool addPCIeRoot = false;
932
    bool addDefaultMemballoon = true;
933 934
    bool addDefaultUSBKBD = false;
    bool addDefaultUSBMouse = false;
935

J
Ján Tomko 已提交
936 937 938 939 940 941
    if (def->os.bootloader || def->os.bootloaderArgs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("bootloader is not supported by QEMU"));
        return -1;
    }

942 943 944 945 946
    /* check for emulator and create a default one if needed */
    if (!def->emulator &&
        !(def->emulator = virDomainDefGetDefaultEmulator(def, caps)))
        return -1;

947 948 949 950 951 952
    /* Add implicit PCI root controller if the machine has one */
    switch (def->os.arch) {
    case VIR_ARCH_I686:
    case VIR_ARCH_X86_64:
        if (!def->os.machine)
            break;
L
Laine Stump 已提交
953
        if (STREQ(def->os.machine, "isapc")) {
954
            addDefaultUSB = false;
955
            break;
956
        }
L
Laine Stump 已提交
957 958 959 960
        if (STRPREFIX(def->os.machine, "pc-q35") ||
            STREQ(def->os.machine, "q35")) {
           addPCIeRoot = true;
           addDefaultUSB = false;
961
           addImplicitSATA = true;
L
Laine Stump 已提交
962 963
           break;
        }
964 965
        if (!STRPREFIX(def->os.machine, "pc-0.") &&
            !STRPREFIX(def->os.machine, "pc-1.") &&
966
            !STRPREFIX(def->os.machine, "pc-i440") &&
967 968 969 970 971 972
            !STREQ(def->os.machine, "pc") &&
            !STRPREFIX(def->os.machine, "rhel"))
            break;
        addPCIRoot = true;
        break;

973 974
    case VIR_ARCH_ARMV7L:
       addDefaultUSB = false;
975
       addDefaultMemballoon = false;
976
       break;
977 978 979 980
    case VIR_ARCH_AARCH64:
       addDefaultUSB = false;
       addDefaultMemballoon = false;
       break;
981

982
    case VIR_ARCH_PPC64:
983
    case VIR_ARCH_PPC64LE:
984 985 986 987 988
        addPCIRoot = true;
        addDefaultUSBKBD = true;
        addDefaultUSBMouse = true;
        break;

989 990 991 992 993 994 995
    case VIR_ARCH_ALPHA:
    case VIR_ARCH_PPC:
    case VIR_ARCH_PPCEMB:
    case VIR_ARCH_SH4:
    case VIR_ARCH_SH4EB:
        addPCIRoot = true;
        break;
996 997 998 999 1000 1001
    case VIR_ARCH_S390:
        addDefaultUSB = false;
        break;
    case VIR_ARCH_S390X:
        addDefaultUSB = false;
        break;
1002 1003 1004 1005
    default:
        break;
    }

1006 1007 1008 1009 1010
    if (addDefaultUSB &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_USB, 0, -1) < 0)
        return -1;

1011 1012 1013 1014 1015
    if (addImplicitSATA &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_SATA, 0, -1) < 0)
        return -1;

1016 1017 1018 1019 1020 1021
    if (addPCIRoot &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
            VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) < 0)
        return -1;

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    /* When a machine has a pcie-root, make sure that there is always
     * a dmi-to-pci-bridge controller added as bus 1, and a pci-bridge
     * as bus 2, so that standard PCI devices can be connected
     */
    if (addPCIeRoot) {
        if (virDomainDefMaybeAddController(
                def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
                VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT) < 0 ||
            virDomainDefMaybeAddController(
                def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 1,
                VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE) < 0 ||
            virDomainDefMaybeAddController(
                def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 2,
                VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE) < 0) {
L
Laine Stump 已提交
1036
        return -1;
1037 1038
        }
    }
1039

1040
    if (addDefaultMemballoon && !def->memballoon) {
1041 1042 1043 1044 1045 1046 1047 1048
        virDomainMemballoonDefPtr memballoon;
        if (VIR_ALLOC(memballoon) < 0)
            return -1;

        memballoon->model = VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO;
        def->memballoon = memballoon;
    }

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    if (addDefaultUSBKBD &&
        def->ngraphics > 0 &&
        virDomainDefMaybeAddInput(def,
                                  VIR_DOMAIN_INPUT_TYPE_KBD,
                                  VIR_DOMAIN_INPUT_BUS_USB) < 0)
        return -1;

    if (addDefaultUSBMouse &&
        def->ngraphics > 0 &&
        virDomainDefMaybeAddInput(def,
                                  VIR_DOMAIN_INPUT_TYPE_MOUSE,
                                  VIR_DOMAIN_INPUT_BUS_USB) < 0)
        return -1;

1063 1064 1065
    return 0;
}

1066
static const char *
1067 1068
qemuDomainDefaultNetModel(const virDomainDef *def)
{
1069
    if (ARCH_IS_S390(def->os.arch))
1070 1071
        return "virtio";

1072 1073
    if (def->os.arch == VIR_ARCH_ARMV7L ||
        def->os.arch == VIR_ARCH_AARCH64) {
1074 1075 1076
        if (STREQ(def->os.machine, "versatilepb"))
            return "smc91c111";

1077 1078 1079
        if (STREQ(def->os.machine, "virt"))
            return "virtio";

1080 1081 1082 1083 1084 1085 1086
        /* Incomplete. vexpress (and a few others) use this, but not all
         * arm boards */
        return "lan9118";
    }

    return "rtl8139";
}
1087

1088 1089
static int
qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
1090
                             const virDomainDef *def,
1091
                             virCapsPtr caps ATTRIBUTE_UNUSED,
1092
                             void *opaque)
1093
{
1094 1095 1096 1097
    int ret = -1;
    virQEMUDriverPtr driver = opaque;
    virQEMUDriverConfigPtr cfg = NULL;

1098
    if (dev->type == VIR_DOMAIN_DEVICE_NET &&
1099 1100
        dev->data.net->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
        !dev->data.net->model) {
1101
        if (VIR_STRDUP(dev->data.net->model,
1102
                       qemuDomainDefaultNetModel(def)) < 0)
1103
            goto cleanup;
1104
    }
1105

1106 1107 1108 1109 1110 1111 1112 1113 1114
    /* set default disk types and drivers */
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        virDomainDiskDefPtr disk = dev->data.disk;

        /* both of these require data from the driver config */
        if (driver && (cfg = virQEMUDriverGetConfig(driver))) {
            /* assign default storage format and driver according to config */
            if (cfg->allowDiskFormatProbing) {
                /* default disk format for drives */
1115
                if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
E
Eric Blake 已提交
1116 1117
                    (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                     virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
1118
                    virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_AUTO);
1119 1120 1121

                 /* default disk format for mirrored drive */
                if (disk->mirror &&
1122 1123
                    disk->mirror->format == VIR_STORAGE_FILE_NONE)
                    disk->mirror->format = VIR_STORAGE_FILE_AUTO;
1124 1125
            } else {
                /* default driver if probing is forbidden */
1126 1127
                if (!virDomainDiskGetDriver(disk) &&
                    virDomainDiskSetDriver(disk, "qemu") < 0)
1128
                        goto cleanup;
1129 1130

                /* default disk format for drives */
1131
                if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
E
Eric Blake 已提交
1132 1133
                    (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                     virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
1134
                    virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);
1135 1136 1137

                 /* default disk format for mirrored drive */
                if (disk->mirror &&
1138 1139
                    disk->mirror->format == VIR_STORAGE_FILE_NONE)
                    disk->mirror->format = VIR_STORAGE_FILE_RAW;
1140
            }
1141 1142 1143
        }
    }

1144 1145 1146 1147
    /* set the default console type for S390 arches */
    if (dev->type == VIR_DOMAIN_DEVICE_CHR &&
        dev->data.chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->data.chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE &&
1148
        ARCH_IS_S390(def->os.arch))
1149 1150
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO;

1151 1152 1153 1154 1155
    /* set the default USB model to none for s390 unless an address is found */
    if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER &&
        dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
        dev->data.controller->model == -1 &&
        dev->data.controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
1156
        ARCH_IS_S390(def->os.arch))
1157 1158
        dev->data.controller->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE;

1159 1160 1161 1162 1163 1164 1165
    /* set the default SCSI controller model for S390 arches */
    if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER &&
        dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI &&
        dev->data.controller->model == -1 &&
        ARCH_IS_S390(def->os.arch))
        dev->data.controller->model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI;

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    /* auto generate unix socket path */
    if (dev->type == VIR_DOMAIN_DEVICE_CHR &&
        dev->data.chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
        dev->data.chr->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO &&
        dev->data.chr->source.type == VIR_DOMAIN_CHR_TYPE_UNIX &&
        !dev->data.chr->source.data.nix.path &&
        (driver && (cfg = virQEMUDriverGetConfig(driver)))) {

        if (virAsprintf(&dev->data.chr->source.data.nix.path,
                        "%s/channel/target/%s.%s",
                        cfg->libDir, def->name,
1177
                        dev->data.chr->target.name) < 0)
1178
            goto cleanup;
1179 1180 1181
        dev->data.chr->source.data.nix.listen = true;
    }

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    /* forbid capabilities mode hostdev in this kind of hypervisor */
    if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
        dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode 'capabilities' is not "
                         "supported in %s"),
                       virDomainVirtTypeToString(def->virtType));
        goto cleanup;
    }

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    if (dev->type == VIR_DOMAIN_DEVICE_VIDEO &&
        dev->data.video->type == VIR_DOMAIN_VIDEO_TYPE_QXL) {
        if (dev->data.video->vgamem) {
            if (dev->data.video->vgamem < 1024) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("value for 'vgamem' must be at least 1 MiB "
                                 "(1024 KiB)"));
                goto cleanup;
            }
            if (dev->data.video->vgamem != VIR_ROUND_UP_POWER_OF_TWO(dev->data.video->vgamem)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("value for 'vgamem' must be power of two"));
                goto cleanup;
            }
        } else {
1207
            dev->data.video->vgamem = QEMU_QXL_VGAMEM_DEFAULT;
1208 1209 1210
        }
    }

1211 1212 1213 1214 1215
    if (dev->type == VIR_DOMAIN_DEVICE_MEMORY &&
        def->mem.max_memory == 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("maxMemory has to be specified when using memory "
                         "devices "));
1216
        goto cleanup;
1217
    }
1218

1219 1220
    ret = 0;

1221
 cleanup:
1222 1223
    virObjectUnref(cfg);
    return ret;
1224 1225 1226 1227 1228
}


virDomainDefParserConfig virQEMUDriverDomainDefParserConfig = {
    .devicesPostParseCallback = qemuDomainDeviceDefPostParse,
1229
    .domainPostParseCallback = qemuDomainDefPostParse,
1230 1231 1232
};


1233
static void
1234
qemuDomainObjSaveJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1235
{
1236 1237 1238
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

    if (virDomainObjIsActive(obj)) {
1239
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, obj) < 0)
1240
            VIR_WARN("Failed to save status on vm %s", obj->def->name);
1241
    }
1242

1243
    virObjectUnref(cfg);
1244 1245
}

J
Jiri Denemark 已提交
1246
void
1247
qemuDomainObjSetJobPhase(virQEMUDriverPtr driver,
J
Jiri Denemark 已提交
1248 1249 1250 1251
                         virDomainObjPtr obj,
                         int phase)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1252
    unsigned long long me = virThreadSelfID();
J
Jiri Denemark 已提交
1253 1254 1255 1256

    if (!priv->job.asyncJob)
        return;

1257 1258 1259 1260 1261
    VIR_DEBUG("Setting '%s' phase to '%s'",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              qemuDomainAsyncJobPhaseToString(priv->job.asyncJob, phase));

    if (priv->job.asyncOwner && me != priv->job.asyncOwner) {
1262
        VIR_WARN("'%s' async job is owned by thread %llu",
1263 1264 1265 1266
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }

J
Jiri Denemark 已提交
1267
    priv->job.phase = phase;
1268
    priv->job.asyncOwner = me;
J
Jiri Denemark 已提交
1269 1270 1271
    qemuDomainObjSaveJob(driver, obj);
}

1272
void
1273 1274
qemuDomainObjSetAsyncJobMask(virDomainObjPtr obj,
                             unsigned long long allowedJobs)
1275 1276 1277
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1278 1279 1280 1281 1282 1283 1284
    if (!priv->job.asyncJob)
        return;

    priv->job.mask = allowedJobs | JOB_MASK(QEMU_JOB_DESTROY);
}

void
1285
qemuDomainObjDiscardAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1286 1287 1288 1289 1290 1291
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    if (priv->job.active == QEMU_JOB_ASYNC_NESTED)
        qemuDomainObjResetJob(priv);
    qemuDomainObjResetAsyncJob(priv);
1292
    qemuDomainObjSaveJob(driver, obj);
1293 1294
}

1295 1296 1297 1298 1299 1300 1301 1302 1303
void
qemuDomainObjReleaseAsyncJob(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    VIR_DEBUG("Releasing ownership of '%s' async job",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob));

    if (priv->job.asyncOwner != virThreadSelfID()) {
1304
        VIR_WARN("'%s' async job is owned by thread %llu",
1305 1306 1307 1308 1309 1310
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }
    priv->job.asyncOwner = 0;
}

1311
static bool
1312
qemuDomainNestedJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
1313 1314
{
    return !priv->job.asyncJob || (priv->job.mask & JOB_MASK(job)) != 0;
1315 1316
}

1317
bool
1318
qemuDomainJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
1319 1320 1321 1322
{
    return !priv->job.active && qemuDomainNestedJobAllowed(priv, job);
}

1323 1324 1325
/* Give up waiting for mutex after 30 seconds */
#define QEMU_JOB_WAIT_TIME (1000ull * 30)

1326
/*
1327
 * obj must be locked before calling
1328
 */
1329
static int ATTRIBUTE_NONNULL(1)
1330
qemuDomainObjBeginJobInternal(virQEMUDriverPtr driver,
1331
                              virDomainObjPtr obj,
1332 1333
                              qemuDomainJob job,
                              qemuDomainAsyncJob asyncJob)
1334 1335
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
J
Jiri Denemark 已提交
1336
    unsigned long long now;
1337
    unsigned long long then;
1338
    bool nested = job == QEMU_JOB_ASYNC_NESTED;
1339
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1340
    const char *blocker = NULL;
J
Jiri Denemark 已提交
1341
    int ret = -1;
J
Jiri Denemark 已提交
1342 1343
    unsigned long long duration = 0;
    unsigned long long asyncDuration = 0;
1344

1345 1346 1347 1348 1349 1350
    VIR_DEBUG("Starting %s: %s (async=%s vm=%p name=%s)",
              job == QEMU_JOB_ASYNC ? "async job" : "job",
              qemuDomainJobTypeToString(job),
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);

1351 1352
    if (virTimeMillisNow(&now) < 0) {
        virObjectUnref(cfg);
1353
        return -1;
1354 1355
    }

1356
    priv->jobs_queued++;
J
Jiri Denemark 已提交
1357
    then = now + QEMU_JOB_WAIT_TIME;
1358

1359
 retry:
1360 1361
    if (cfg->maxQueuedJobs &&
        priv->jobs_queued > cfg->maxQueuedJobs) {
1362 1363 1364
        goto error;
    }

1365
    while (!nested && !qemuDomainNestedJobAllowed(priv, job)) {
1366
        VIR_DEBUG("Waiting for async job (vm=%p name=%s)", obj, obj->def->name);
1367
        if (virCondWaitUntil(&priv->job.asyncCond, &obj->parent.lock, then) < 0)
1368 1369 1370
            goto error;
    }

1371
    while (priv->job.active) {
1372
        VIR_DEBUG("Waiting for job (vm=%p name=%s)", obj, obj->def->name);
1373
        if (virCondWaitUntil(&priv->job.cond, &obj->parent.lock, then) < 0)
1374
            goto error;
1375
    }
1376 1377 1378

    /* No job is active but a new async job could have been started while obj
     * was unlocked, so we need to recheck it. */
1379
    if (!nested && !qemuDomainNestedJobAllowed(priv, job))
1380 1381
        goto retry;

1382
    qemuDomainObjResetJob(priv);
1383

J
Jiri Denemark 已提交
1384 1385
    ignore_value(virTimeMillisNow(&now));

1386
    if (job != QEMU_JOB_ASYNC) {
1387
        VIR_DEBUG("Started job: %s (async=%s vm=%p name=%s)",
1388
                   qemuDomainJobTypeToString(job),
1389 1390
                  qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                  obj, obj->def->name);
1391
        priv->job.active = job;
1392
        priv->job.owner = virThreadSelfID();
1393
        priv->job.ownerAPI = virThreadJobGet();
J
Jiri Denemark 已提交
1394
        priv->job.started = now;
1395
    } else {
1396 1397 1398
        VIR_DEBUG("Started async job: %s (vm=%p name=%s)",
                  qemuDomainAsyncJobTypeToString(asyncJob),
                  obj, obj->def->name);
1399
        qemuDomainObjResetAsyncJob(priv);
J
Jiri Denemark 已提交
1400 1401
        if (VIR_ALLOC(priv->job.current) < 0)
            goto cleanup;
1402
        priv->job.asyncJob = asyncJob;
1403
        priv->job.asyncOwner = virThreadSelfID();
1404
        priv->job.asyncOwnerAPI = virThreadJobGet();
J
Jiri Denemark 已提交
1405
        priv->job.asyncStarted = now;
J
Jiri Denemark 已提交
1406
        priv->job.current->started = now;
1407
    }
1408

1409 1410
    if (qemuDomainTrackJob(job))
        qemuDomainObjSaveJob(driver, obj);
1411

1412
    virObjectUnref(cfg);
1413
    return 0;
1414

1415
 error:
J
Jiri Denemark 已提交
1416 1417 1418 1419 1420 1421
    ignore_value(virTimeMillisNow(&now));
    if (priv->job.active && priv->job.started)
        duration = now - priv->job.started;
    if (priv->job.asyncJob && priv->job.asyncStarted)
        asyncDuration = now - priv->job.asyncStarted;

1422
    VIR_WARN("Cannot start job (%s, %s) for domain %s; "
J
Jiri Denemark 已提交
1423 1424
             "current job is (%s, %s) owned by (%llu %s, %llu %s) "
             "for (%llus, %llus)",
1425 1426 1427 1428 1429
             qemuDomainJobTypeToString(job),
             qemuDomainAsyncJobTypeToString(asyncJob),
             obj->def->name,
             qemuDomainJobTypeToString(priv->job.active),
             qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
1430
             priv->job.owner, NULLSTR(priv->job.ownerAPI),
J
Jiri Denemark 已提交
1431 1432
             priv->job.asyncOwner, NULLSTR(priv->job.asyncOwnerAPI),
             duration / 1000, asyncDuration / 1000);
1433 1434 1435 1436 1437

    if (nested || qemuDomainNestedJobAllowed(priv, job))
        blocker = priv->job.ownerAPI;
    else
        blocker = priv->job.asyncOwnerAPI;
1438

1439 1440
    ret = -1;
    if (errno == ETIMEDOUT) {
1441 1442 1443 1444 1445 1446 1447 1448
        if (blocker) {
            virReportError(VIR_ERR_OPERATION_TIMEOUT,
                           _("cannot acquire state change lock (held by %s)"),
                           blocker);
        } else {
            virReportError(VIR_ERR_OPERATION_TIMEOUT, "%s",
                           _("cannot acquire state change lock"));
        }
1449 1450 1451
        ret = -2;
    } else if (cfg->maxQueuedJobs &&
               priv->jobs_queued > cfg->maxQueuedJobs) {
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
        if (blocker) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("cannot acquire state change lock (held by %s) "
                             "due to max_queued limit"),
                           blocker);
        } else {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot acquire state change lock "
                             "due to max_queued limit"));
        }
1462 1463
        ret = -2;
    } else {
1464
        virReportSystemError(errno, "%s", _("cannot acquire job mutex"));
1465
    }
J
Jiri Denemark 已提交
1466 1467

 cleanup:
1468
    priv->jobs_queued--;
1469
    virObjectUnref(cfg);
1470
    return ret;
1471 1472 1473
}

/*
1474
 * obj must be locked before calling
1475 1476 1477 1478
 *
 * This must be called by anything that will change the VM state
 * in any way, or anything that will use the QEMU monitor.
 *
1479
 * Successful calls must be followed by EndJob eventually
1480
 */
1481
int qemuDomainObjBeginJob(virQEMUDriverPtr driver,
1482
                          virDomainObjPtr obj,
1483
                          qemuDomainJob job)
1484
{
1485 1486 1487 1488 1489
    if (qemuDomainObjBeginJobInternal(driver, obj, job,
                                      QEMU_ASYNC_JOB_NONE) < 0)
        return -1;
    else
        return 0;
1490 1491
}

1492
int qemuDomainObjBeginAsyncJob(virQEMUDriverPtr driver,
1493
                               virDomainObjPtr obj,
1494
                               qemuDomainAsyncJob asyncJob)
1495
{
1496 1497 1498 1499 1500
    if (qemuDomainObjBeginJobInternal(driver, obj, QEMU_JOB_ASYNC,
                                      asyncJob) < 0)
        return -1;
    else
        return 0;
1501 1502
}

1503
static int ATTRIBUTE_RETURN_CHECK
1504 1505
qemuDomainObjBeginNestedJob(virQEMUDriverPtr driver,
                            virDomainObjPtr obj,
1506
                            qemuDomainAsyncJob asyncJob)
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    if (asyncJob != priv->job.asyncJob) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected async job %d"), asyncJob);
        return -1;
    }

    if (priv->job.asyncOwner != virThreadSelfID()) {
1517
        VIR_WARN("This thread doesn't seem to be the async job owner: %llu",
1518 1519 1520 1521 1522 1523 1524 1525
                 priv->job.asyncOwner);
    }

    return qemuDomainObjBeginJobInternal(driver, obj,
                                         QEMU_JOB_ASYNC_NESTED,
                                         QEMU_ASYNC_JOB_NONE);
}

1526

1527
/*
1528
 * obj must be locked and have a reference before calling
1529 1530 1531 1532
 *
 * To be called after completing the work associated with the
 * earlier qemuDomainBeginJob() call
 */
1533 1534
void
qemuDomainObjEndJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1535 1536
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1537
    qemuDomainJob job = priv->job.active;
1538

1539 1540
    priv->jobs_queued--;

1541
    VIR_DEBUG("Stopping job: %s (async=%s vm=%p name=%s)",
1542
              qemuDomainJobTypeToString(job),
1543 1544
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
1545

1546
    qemuDomainObjResetJob(priv);
1547 1548
    if (qemuDomainTrackJob(job))
        qemuDomainObjSaveJob(driver, obj);
1549
    virCondSignal(&priv->job.cond);
1550 1551
}

1552
void
1553
qemuDomainObjEndAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1554 1555
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1556

1557 1558
    priv->jobs_queued--;

1559 1560 1561
    VIR_DEBUG("Stopping async job: %s (vm=%p name=%s)",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
1562

1563
    qemuDomainObjResetAsyncJob(priv);
1564
    qemuDomainObjSaveJob(driver, obj);
1565 1566 1567
    virCondBroadcast(&priv->job.asyncCond);
}

1568 1569 1570 1571 1572
void
qemuDomainObjAbortAsyncJob(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1573 1574 1575
    VIR_DEBUG("Requesting abort of async job: %s (vm=%p name=%s)",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
1576 1577 1578 1579

    priv->job.asyncAbort = true;
}

1580 1581 1582 1583 1584 1585 1586 1587 1588
/*
 * obj must be locked before calling
 *
 * To be called immediately before any QEMU monitor API call
 * Must have already either called qemuDomainObjBeginJob() and checked
 * that the VM is still active; may not be used for nested async jobs.
 *
 * To be followed with qemuDomainObjExitMonitor() once complete
 */
1589
static int
1590
qemuDomainObjEnterMonitorInternal(virQEMUDriverPtr driver,
1591
                                  virDomainObjPtr obj,
1592
                                  qemuDomainAsyncJob asyncJob)
1593 1594 1595
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1596
    if (asyncJob != QEMU_ASYNC_JOB_NONE) {
1597 1598 1599
        int ret;
        if ((ret = qemuDomainObjBeginNestedJob(driver, obj, asyncJob)) < 0)
            return ret;
1600
        if (!virDomainObjIsActive(obj)) {
1601 1602
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
1603
            qemuDomainObjEndJob(driver, obj);
1604 1605
            return -1;
        }
1606 1607 1608
    } else if (priv->job.asyncOwner == virThreadSelfID()) {
        VIR_WARN("This thread seems to be the async job owner; entering"
                 " monitor without asking for a nested job is dangerous");
1609 1610
    }

1611 1612
    VIR_DEBUG("Entering monitor (mon=%p vm=%p name=%s)",
              priv->mon, obj, obj->def->name);
1613
    virObjectLock(priv->mon);
1614
    virObjectRef(priv->mon);
1615
    ignore_value(virTimeMillisNow(&priv->monStart));
1616
    virObjectUnlock(obj);
1617 1618

    return 0;
1619 1620
}

1621
static void ATTRIBUTE_NONNULL(1)
1622
qemuDomainObjExitMonitorInternal(virQEMUDriverPtr driver,
1623
                                 virDomainObjPtr obj)
1624 1625
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1626
    bool hasRefs;
1627

1628
    hasRefs = virObjectUnref(priv->mon);
1629

1630
    if (hasRefs)
1631
        virObjectUnlock(priv->mon);
1632

1633
    virObjectLock(obj);
1634 1635
    VIR_DEBUG("Exited monitor (mon=%p vm=%p name=%s)",
              priv->mon, obj, obj->def->name);
1636

1637
    priv->monStart = 0;
1638
    if (!hasRefs)
1639
        priv->mon = NULL;
1640

1641 1642 1643 1644 1645
    if (priv->job.active == QEMU_JOB_ASYNC_NESTED) {
        qemuDomainObjResetJob(priv);
        qemuDomainObjSaveJob(driver, obj);
        virCondSignal(&priv->job.cond);
    }
1646 1647
}

1648
void qemuDomainObjEnterMonitor(virQEMUDriverPtr driver,
1649
                               virDomainObjPtr obj)
1650
{
1651
    ignore_value(qemuDomainObjEnterMonitorInternal(driver, obj,
1652
                                                   QEMU_ASYNC_JOB_NONE));
1653 1654
}

1655
/* obj must NOT be locked before calling
1656 1657
 *
 * Should be paired with an earlier qemuDomainObjEnterMonitor() call
1658 1659 1660 1661 1662 1663
 *
 * Returns -1 if the domain is no longer alive after exiting the monitor.
 * In that case, the caller should be careful when using obj's data,
 * e.g. the live definition in vm->def has been freed by qemuProcessStop
 * and replaced by the persistent definition, so pointers stolen
 * from the live definition could no longer be valid.
1664
 */
1665 1666
int qemuDomainObjExitMonitor(virQEMUDriverPtr driver,
                             virDomainObjPtr obj)
1667
{
1668
    qemuDomainObjExitMonitorInternal(driver, obj);
1669
    if (!virDomainObjIsActive(obj)) {
1670 1671 1672
        if (!virGetLastError())
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
1673 1674 1675
        return -1;
    }
    return 0;
1676
}
1677 1678

/*
1679
 * obj must be locked before calling
1680 1681
 *
 * To be called immediately before any QEMU monitor API call.
1682
 * Must have already either called qemuDomainObjBeginJob()
1683 1684 1685 1686 1687
 * and checked that the VM is still active, with asyncJob of
 * QEMU_ASYNC_JOB_NONE; or already called qemuDomainObjBeginAsyncJob,
 * with the same asyncJob.
 *
 * Returns 0 if job was started, in which case this must be followed with
1688 1689 1690
 * qemuDomainObjExitMonitor(); -2 if waiting for the nested job times out;
 * or -1 if the job could not be started (probably because the vm exited
 * in the meantime).
1691 1692
 */
int
1693
qemuDomainObjEnterMonitorAsync(virQEMUDriverPtr driver,
1694
                               virDomainObjPtr obj,
1695
                               qemuDomainAsyncJob asyncJob)
1696
{
1697
    return qemuDomainObjEnterMonitorInternal(driver, obj, asyncJob);
1698 1699
}

D
Daniel P. Berrange 已提交
1700 1701


1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
/*
 * obj must be locked before calling
 *
 * To be called immediately before any QEMU agent API call.
 * Must have already called qemuDomainObjBeginJob() and checked
 * that the VM is still active.
 *
 * To be followed with qemuDomainObjExitAgent() once complete
 */
void
qemuDomainObjEnterAgent(virDomainObjPtr obj)
D
Daniel P. Berrange 已提交
1713 1714 1715
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1716 1717
    VIR_DEBUG("Entering agent (agent=%p vm=%p name=%s)",
              priv->agent, obj, obj->def->name);
1718
    virObjectLock(priv->agent);
1719
    virObjectRef(priv->agent);
D
Daniel P. Berrange 已提交
1720
    ignore_value(virTimeMillisNow(&priv->agentStart));
1721
    virObjectUnlock(obj);
D
Daniel P. Berrange 已提交
1722 1723
}

1724 1725 1726 1727 1728 1729 1730

/* obj must NOT be locked before calling
 *
 * Should be paired with an earlier qemuDomainObjEnterAgent() call
 */
void
qemuDomainObjExitAgent(virDomainObjPtr obj)
D
Daniel P. Berrange 已提交
1731 1732
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1733
    bool hasRefs;
D
Daniel P. Berrange 已提交
1734

1735
    hasRefs = virObjectUnref(priv->agent);
D
Daniel P. Berrange 已提交
1736

1737
    if (hasRefs)
1738
        virObjectUnlock(priv->agent);
D
Daniel P. Berrange 已提交
1739

1740
    virObjectLock(obj);
1741 1742
    VIR_DEBUG("Exited agent (agent=%p vm=%p name=%s)",
              priv->agent, obj, obj->def->name);
D
Daniel P. Berrange 已提交
1743 1744

    priv->agentStart = 0;
1745
    if (!hasRefs)
D
Daniel P. Berrange 已提交
1746 1747 1748
        priv->agent = NULL;
}

1749
void qemuDomainObjEnterRemote(virDomainObjPtr obj)
1750
{
1751 1752
    VIR_DEBUG("Entering remote (vm=%p name=%s)",
              obj, obj->def->name);
1753
    virObjectUnlock(obj);
1754 1755
}

1756
void qemuDomainObjExitRemote(virDomainObjPtr obj)
1757
{
1758
    virObjectLock(obj);
1759 1760
    VIR_DEBUG("Exited remote (vm=%p name=%s)",
              obj, obj->def->name);
1761
}
1762 1763


1764 1765 1766 1767 1768 1769 1770 1771
virDomainDefPtr
qemuDomainDefCopy(virQEMUDriverPtr driver,
                  virDomainDefPtr src,
                  unsigned int flags)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    virDomainDefPtr ret = NULL;
    virCapsPtr caps = NULL;
1772
    char *xml = NULL;
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

    if (qemuDomainDefFormatBuf(driver, src, flags, &buf) < 0)
        goto cleanup;

    xml = virBufferContentAndReset(&buf);

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

    if (!(ret = virDomainDefParseString(xml, caps, driver->xmlopt,
                                        QEMU_EXPECTED_VIRT_TYPES,
1784
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
1785 1786
        goto cleanup;

1787
 cleanup:
1788 1789 1790 1791 1792
    VIR_FREE(xml);
    virObjectUnref(caps);
    return ret;
}

1793
int
1794
qemuDomainDefFormatBuf(virQEMUDriverPtr driver,
1795 1796 1797
                       virDomainDefPtr def,
                       unsigned int flags,
                       virBuffer *buf)
1798
{
1799
    int ret = -1;
1800
    virCPUDefPtr cpu = NULL;
1801
    virCPUDefPtr def_cpu = def->cpu;
1802 1803
    virDomainControllerDefPtr *controllers = NULL;
    int ncontrollers = 0;
1804 1805 1806 1807
    virCapsPtr caps = NULL;

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

    /* Update guest CPU requirements according to host CPU */
1810 1811 1812
    if ((flags & VIR_DOMAIN_XML_UPDATE_CPU) &&
        def_cpu &&
        (def_cpu->mode != VIR_CPU_MODE_CUSTOM || def_cpu->model)) {
1813 1814
        if (!caps->host.cpu ||
            !caps->host.cpu->model) {
1815 1816
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("cannot get host CPU capabilities"));
1817 1818 1819
            goto cleanup;
        }

1820
        if (!(cpu = virCPUDefCopy(def_cpu)) ||
1821
            cpuUpdate(cpu, caps->host.cpu) < 0)
1822 1823 1824 1825
            goto cleanup;
        def->cpu = cpu;
    }

1826
    if ((flags & VIR_DOMAIN_XML_MIGRATABLE)) {
1827
        size_t i;
1828
        int toremove = 0;
1829
        virDomainControllerDefPtr usb = NULL, pci = NULL;
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847

        /* If only the default USB controller is present, we can remove it
         * and make the XML compatible with older versions of libvirt which
         * didn't support USB controllers in the XML but always added the
         * default one to qemu anyway.
         */
        for (i = 0; i < def->ncontrollers; i++) {
            if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_USB) {
                if (usb) {
                    usb = NULL;
                    break;
                }
                usb = def->controllers[i];
            }
        }
        if (usb && usb->idx == 0 && usb->model == -1) {
            VIR_DEBUG("Removing default USB controller from domain '%s'"
                      " for migration compatibility", def->name);
1848
            toremove++;
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
        } else {
            usb = NULL;
        }

        /* Remove the default PCI controller if there is only one present
         * and its model is pci-root */
        for (i = 0; i < def->ncontrollers; i++) {
            if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
                if (pci) {
                    pci = NULL;
                    break;
                }
                pci = def->controllers[i];
            }
        }

        if (pci && pci->idx == 0 &&
            pci->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) {
L
Laine Stump 已提交
1867
            VIR_DEBUG("Removing default pci-root from domain '%s'"
1868
                      " for migration compatibility", def->name);
1869
            toremove++;
1870 1871 1872 1873
        } else {
            pci = NULL;
        }

1874
        if (toremove) {
1875 1876
            controllers = def->controllers;
            ncontrollers = def->ncontrollers;
1877
            if (VIR_ALLOC_N(def->controllers, ncontrollers - toremove) < 0) {
1878 1879 1880 1881 1882 1883
                controllers = NULL;
                goto cleanup;
            }

            def->ncontrollers = 0;
            for (i = 0; i < ncontrollers; i++) {
1884
                if (controllers[i] != usb && controllers[i] != pci)
1885 1886 1887
                    def->controllers[def->ncontrollers++] = controllers[i];
            }
        }
1888 1889


1890 1891
    }

1892 1893 1894
    ret = virDomainDefFormatInternal(def,
                                     virDomainDefFormatConvertXMLFlags(flags),
                                     buf);
1895

1896
 cleanup:
1897 1898
    def->cpu = def_cpu;
    virCPUDefFree(cpu);
1899 1900 1901 1902 1903
    if (controllers) {
        VIR_FREE(def->controllers);
        def->controllers = controllers;
        def->ncontrollers = ncontrollers;
    }
1904
    virObjectUnref(caps);
1905 1906
    return ret;
}
1907

1908
char *qemuDomainDefFormatXML(virQEMUDriverPtr driver,
1909
                             virDomainDefPtr def,
1910
                             unsigned int flags)
1911 1912 1913
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

1914
    if (qemuDomainDefFormatBuf(driver, def, flags, &buf) < 0) {
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
        virBufferFreeAndReset(&buf);
        return NULL;
    }

    if (virBufferError(&buf)) {
        virReportOOMError();
        virBufferFreeAndReset(&buf);
        return NULL;
    }

    return virBufferContentAndReset(&buf);
}

1928
char *qemuDomainFormatXML(virQEMUDriverPtr driver,
1929
                          virDomainObjPtr vm,
1930
                          unsigned int flags)
1931 1932 1933 1934 1935 1936 1937 1938
{
    virDomainDefPtr def;

    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
        def = vm->newDef;
    else
        def = vm->def;

1939
    return qemuDomainDefFormatXML(driver, def, flags);
1940 1941
}

1942
char *
1943
qemuDomainDefFormatLive(virQEMUDriverPtr driver,
1944
                        virDomainDefPtr def,
1945 1946
                        bool inactive,
                        bool compatible)
1947 1948 1949 1950 1951
{
    unsigned int flags = QEMU_DOMAIN_FORMAT_LIVE_FLAGS;

    if (inactive)
        flags |= VIR_DOMAIN_XML_INACTIVE;
1952 1953
    if (compatible)
        flags |= VIR_DOMAIN_XML_MIGRATABLE;
1954

1955
    return qemuDomainDefFormatXML(driver, def, flags);
1956 1957
}

1958

1959
void qemuDomainObjTaint(virQEMUDriverPtr driver,
1960
                        virDomainObjPtr obj,
1961
                        virDomainTaintFlags taint,
1962
                        int logFD)
1963
{
1964 1965
    virErrorPtr orig_err = NULL;

1966 1967 1968 1969 1970 1971 1972 1973 1974
    if (virDomainObjTaint(obj, taint)) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->def->uuid, uuidstr);

        VIR_WARN("Domain id=%d name='%s' uuid=%s is tainted: %s",
                 obj->def->id,
                 obj->def->name,
                 uuidstr,
                 virDomainTaintTypeToString(taint));
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988

        /* We don't care about errors logging taint info, so
         * preserve original error, and clear any error that
         * is raised */
        orig_err = virSaveLastError();
        if (qemuDomainAppendLog(driver, obj, logFD,
                                "Domain id=%d is tainted: %s\n",
                                obj->def->id,
                                virDomainTaintTypeToString(taint)) < 0)
            virResetLastError();
        if (orig_err) {
            virSetError(orig_err);
            virFreeError(orig_err);
        }
1989 1990 1991 1992
    }
}


1993
void qemuDomainObjCheckTaint(virQEMUDriverPtr driver,
1994 1995
                             virDomainObjPtr obj,
                             int logFD)
1996
{
1997
    size_t i;
1998
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1999
    qemuDomainObjPrivatePtr priv = obj->privateData;
2000

2001 2002 2003 2004
    if (cfg->privileged &&
        (!cfg->clearEmulatorCapabilities ||
         cfg->user == 0 ||
         cfg->group == 0))
2005
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES, logFD);
2006

2007 2008 2009
    if (priv->hookRun)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOOK, logFD);

2010 2011 2012
    if (obj->def->namespaceData) {
        qemuDomainCmdlineDefPtr qemucmd = obj->def->namespaceData;
        if (qemucmd->num_args || qemucmd->num_env)
2013
            qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_ARGV, logFD);
2014 2015
    }

2016 2017 2018
    if (obj->def->cpu && obj->def->cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOST_CPU, logFD);

2019
    for (i = 0; i < obj->def->ndisks; i++)
2020
        qemuDomainObjCheckDiskTaint(driver, obj, obj->def->disks[i], logFD);
2021

2022 2023 2024 2025
    for (i = 0; i < obj->def->nhostdevs; i++)
        qemuDomainObjCheckHostdevTaint(driver, obj, obj->def->hostdevs[i],
                                       logFD);

2026
    for (i = 0; i < obj->def->nnets; i++)
2027
        qemuDomainObjCheckNetTaint(driver, obj, obj->def->nets[i], logFD);
2028 2029

    virObjectUnref(cfg);
2030 2031 2032
}


2033
void qemuDomainObjCheckDiskTaint(virQEMUDriverPtr driver,
2034
                                 virDomainObjPtr obj,
2035 2036
                                 virDomainDiskDefPtr disk,
                                 int logFD)
2037
{
2038
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2039
    int format = virDomainDiskGetFormat(disk);
2040

2041
    if ((!format || format == VIR_STORAGE_FILE_AUTO) &&
2042
        cfg->allowDiskFormatProbing)
2043
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_DISK_PROBING, logFD);
2044

2045 2046 2047
    if (disk->rawio == VIR_TRISTATE_BOOL_YES)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES,
                           logFD);
2048 2049

    virObjectUnref(cfg);
2050 2051 2052
}


2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
void qemuDomainObjCheckHostdevTaint(virQEMUDriverPtr driver,
                                    virDomainObjPtr obj,
                                    virDomainHostdevDefPtr hostdev,
                                    int logFD)
{
    virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;

    if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->rawio == VIR_TRISTATE_BOOL_YES)
            qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES,
                               logFD);
}


2067
void qemuDomainObjCheckNetTaint(virQEMUDriverPtr driver,
2068
                                virDomainObjPtr obj,
2069 2070
                                virDomainNetDefPtr net,
                                int logFD)
2071
{
2072 2073 2074 2075 2076 2077
    /* script is only useful for NET_TYPE_ETHERNET (qemu) and
     * NET_TYPE_BRIDGE (xen), but could be (incorrectly) specified for
     * any interface type. In any case, it's adding user sauce into
     * the soup, so it should taint the domain.
     */
    if (net->script != NULL)
2078
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_SHELL_SCRIPTS, logFD);
2079
}
2080 2081 2082


static int
2083
qemuDomainOpenLogHelper(virQEMUDriverConfigPtr cfg,
2084
                        virDomainObjPtr vm,
E
Eric Blake 已提交
2085
                        int oflags,
2086 2087 2088 2089
                        mode_t mode)
{
    char *logfile;
    int fd = -1;
2090
    bool trunc = false;
2091

2092
    if (virAsprintf(&logfile, "%s/%s.log", cfg->logDir, vm->def->name) < 0)
2093 2094
        return -1;

2095 2096 2097 2098 2099 2100 2101 2102 2103
    /* To make SELinux happy we always need to open in append mode.
     * So we fake O_TRUNC by calling ftruncate after open instead
     */
    if (oflags & O_TRUNC) {
        oflags &= ~O_TRUNC;
        oflags |= O_APPEND;
        trunc = true;
    }

E
Eric Blake 已提交
2104
    if ((fd = open(logfile, oflags, mode)) < 0) {
2105 2106 2107 2108 2109 2110 2111
        virReportSystemError(errno, _("failed to create logfile %s"),
                             logfile);
        goto cleanup;
    }
    if (virSetCloseExec(fd) < 0) {
        virReportSystemError(errno, _("failed to set close-on-exec flag on %s"),
                             logfile);
2112 2113 2114 2115 2116 2117 2118
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }
    if (trunc &&
        ftruncate(fd, 0) < 0) {
        virReportSystemError(errno, _("failed to truncate %s"),
                             logfile);
2119 2120 2121 2122
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }

2123
 cleanup:
2124 2125 2126 2127 2128 2129
    VIR_FREE(logfile);
    return fd;
}


int
2130
qemuDomainCreateLog(virQEMUDriverPtr driver, virDomainObjPtr vm,
E
Eric Blake 已提交
2131
                    bool append)
2132
{
2133
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
E
Eric Blake 已提交
2134
    int oflags;
2135
    int ret;
2136

E
Eric Blake 已提交
2137
    oflags = O_CREAT | O_WRONLY;
2138
    /* Only logrotate files in /var/log, so only append if running privileged */
2139
    if (cfg->privileged || append)
E
Eric Blake 已提交
2140
        oflags |= O_APPEND;
2141
    else
E
Eric Blake 已提交
2142
        oflags |= O_TRUNC;
2143

2144 2145 2146
    ret = qemuDomainOpenLogHelper(cfg, vm, oflags, S_IRUSR | S_IWUSR);
    virObjectUnref(cfg);
    return ret;
2147 2148 2149 2150
}


int
2151
qemuDomainOpenLog(virQEMUDriverPtr driver, virDomainObjPtr vm, off_t pos)
2152
{
2153
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2154 2155 2156 2157
    int fd;
    off_t off;
    int whence;

2158 2159 2160
    fd = qemuDomainOpenLogHelper(cfg, vm, O_RDONLY, 0);
    virObjectUnref(cfg);
    if (fd < 0)
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
        return -1;

    if (pos < 0) {
        off = 0;
        whence = SEEK_END;
    } else {
        off = pos;
        whence = SEEK_SET;
    }

    if (lseek(fd, off, whence) < 0) {
        if (whence == SEEK_END)
            virReportSystemError(errno,
                                 _("unable to seek to end of log for %s"),
                                 vm->def->name);
        else
            virReportSystemError(errno,
                                 _("unable to seek to %lld from start for %s"),
                                 (long long)off, vm->def->name);
        VIR_FORCE_CLOSE(fd);
    }

    return fd;
}


2187
int qemuDomainAppendLog(virQEMUDriverPtr driver,
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
                        virDomainObjPtr obj,
                        int logFD,
                        const char *fmt, ...)
{
    int fd = logFD;
    va_list argptr;
    char *message = NULL;
    int ret = -1;

    va_start(argptr, fmt);

    if ((fd == -1) &&
        (fd = qemuDomainCreateLog(driver, obj, true)) < 0)
        goto cleanup;

2203
    if (virVasprintf(&message, fmt, argptr) < 0)
2204 2205 2206 2207 2208 2209 2210 2211 2212
        goto cleanup;
    if (safewrite(fd, message, strlen(message)) < 0) {
        virReportSystemError(errno, _("Unable to write to domain logfile %s"),
                             obj->def->name);
        goto cleanup;
    }

    ret = 0;

2213
 cleanup:
2214 2215 2216 2217 2218
    va_end(argptr);

    if (fd != logFD)
        VIR_FORCE_CLOSE(fd);

O
Osier Yang 已提交
2219
    VIR_FREE(message);
2220 2221
    return ret;
}
2222 2223 2224

/* Locate an appropriate 'qemu-img' binary.  */
const char *
2225
qemuFindQemuImgBinary(virQEMUDriverPtr driver)
2226
{
2227 2228 2229
    if (!driver->qemuImgBinary)
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unable to find kvm-img or qemu-img"));
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245

    return driver->qemuImgBinary;
}

int
qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                virDomainSnapshotObjPtr snapshot,
                                char *snapshotDir)
{
    char *newxml = NULL;
    int ret = -1;
    char *snapDir = NULL;
    char *snapFile = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
2246 2247 2248 2249
    newxml = virDomainSnapshotDefFormat(
        uuidstr, snapshot->def,
        virDomainDefFormatConvertXMLFlags(QEMU_DOMAIN_FORMAT_LIVE_FLAGS),
        1);
2250
    if (newxml == NULL)
2251 2252
        return -1;

2253
    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0)
2254 2255 2256 2257 2258 2259 2260
        goto cleanup;
    if (virFileMakePath(snapDir) < 0) {
        virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
                             snapDir);
        goto cleanup;
    }

2261
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0)
2262 2263
        goto cleanup;

J
Ján Tomko 已提交
2264
    ret = virXMLSaveFile(snapFile, NULL, "snapshot-edit", newxml);
2265

2266
 cleanup:
2267 2268 2269 2270 2271 2272 2273 2274
    VIR_FREE(snapFile);
    VIR_FREE(snapDir);
    VIR_FREE(newxml);
    return ret;
}

/* The domain is expected to be locked and inactive. Return -1 on normal
 * failure, 1 if we skipped a disk due to try_all.  */
2275
static int
2276
qemuDomainSnapshotForEachQcow2Raw(virQEMUDriverPtr driver,
2277 2278 2279 2280 2281
                                  virDomainDefPtr def,
                                  const char *name,
                                  const char *op,
                                  bool try_all,
                                  int ndisks)
2282 2283
{
    const char *qemuimgarg[] = { NULL, "snapshot", NULL, NULL, NULL, NULL };
2284
    size_t i;
2285 2286 2287 2288 2289 2290 2291 2292 2293
    bool skipped = false;

    qemuimgarg[0] = qemuFindQemuImgBinary(driver);
    if (qemuimgarg[0] == NULL) {
        /* qemuFindQemuImgBinary set the error */
        return -1;
    }

    qemuimgarg[2] = op;
2294
    qemuimgarg[3] = name;
2295

2296
    for (i = 0; i < ndisks; i++) {
2297
        /* FIXME: we also need to handle LVM here */
2298
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
2299 2300 2301
            int format = virDomainDiskGetFormat(def->disks[i]);

            if (format > 0 && format != VIR_STORAGE_FILE_QCOW2) {
2302 2303 2304 2305 2306
                if (try_all) {
                    /* Continue on even in the face of error, since other
                     * disks in this VM may have the same snapshot name.
                     */
                    VIR_WARN("skipping snapshot action on %s",
2307
                             def->disks[i]->dst);
2308 2309
                    skipped = true;
                    continue;
2310 2311 2312 2313 2314
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
2315
                }
2316 2317 2318 2319
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Disk device '%s' does not support"
                                 " snapshotting"),
                               def->disks[i]->dst);
2320 2321 2322
                return -1;
            }

2323
            qemuimgarg[4] = virDomainDiskGetSource(def->disks[i]);
2324 2325 2326 2327

            if (virRun(qemuimgarg, NULL) < 0) {
                if (try_all) {
                    VIR_WARN("skipping snapshot action on %s",
2328
                             def->disks[i]->dst);
2329 2330
                    skipped = true;
                    continue;
2331 2332 2333 2334 2335
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
2336 2337 2338 2339 2340 2341 2342 2343 2344
                }
                return -1;
            }
        }
    }

    return skipped ? 1 : 0;
}

2345 2346 2347
/* The domain is expected to be locked and inactive. Return -1 on normal
 * failure, 1 if we skipped a disk due to try_all.  */
int
2348
qemuDomainSnapshotForEachQcow2(virQEMUDriverPtr driver,
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
                               virDomainObjPtr vm,
                               virDomainSnapshotObjPtr snap,
                               const char *op,
                               bool try_all)
{
    /* Prefer action on the disks in use at the time the snapshot was
     * created; but fall back to current definition if dealing with a
     * snapshot created prior to libvirt 0.9.5.  */
    virDomainDefPtr def = snap->def->dom;

    if (!def)
        def = vm->def;
    return qemuDomainSnapshotForEachQcow2Raw(driver, def, snap->def->name,
                                             op, try_all, def->ndisks);
}

2365 2366
/* Discard one snapshot (or its metadata), without reparenting any children.  */
int
2367
qemuDomainSnapshotDiscard(virQEMUDriverPtr driver,
2368 2369 2370 2371 2372 2373 2374 2375 2376
                          virDomainObjPtr vm,
                          virDomainSnapshotObjPtr snap,
                          bool update_current,
                          bool metadata_only)
{
    char *snapFile = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap = NULL;
2377
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2378 2379 2380 2381 2382 2383 2384 2385 2386

    if (!metadata_only) {
        if (!virDomainObjIsActive(vm)) {
            /* Ignore any skipped disks */
            if (qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-d",
                                               true) < 0)
                goto cleanup;
        } else {
            priv = vm->privateData;
2387
            qemuDomainObjEnterMonitor(driver, vm);
2388 2389
            /* we continue on even in the face of error */
            qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
2390
            ignore_value(qemuDomainObjExitMonitor(driver, vm));
2391 2392 2393
        }
    }

2394
    if (virAsprintf(&snapFile, "%s/%s/%s.xml", cfg->snapshotDir,
2395
                    vm->def->name, snap->def->name) < 0)
2396 2397 2398 2399
        goto cleanup;

    if (snap == vm->current_snapshot) {
        if (update_current && snap->def->parent) {
2400
            parentsnap = virDomainSnapshotFindByName(vm->snapshots,
2401 2402 2403 2404 2405 2406 2407
                                                     snap->def->parent);
            if (!parentsnap) {
                VIR_WARN("missing parent snapshot matching name '%s'",
                         snap->def->parent);
            } else {
                parentsnap->def->current = true;
                if (qemuDomainSnapshotWriteMetadata(vm, parentsnap,
2408
                                                    cfg->snapshotDir) < 0) {
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
                    VIR_WARN("failed to set parent snapshot '%s' as current",
                             snap->def->parent);
                    parentsnap->def->current = false;
                    parentsnap = NULL;
                }
            }
        }
        vm->current_snapshot = parentsnap;
    }

    if (unlink(snapFile) < 0)
        VIR_WARN("Failed to unlink %s", snapFile);
2421
    virDomainSnapshotObjListRemove(vm->snapshots, snap);
2422 2423 2424

    ret = 0;

2425
 cleanup:
2426
    VIR_FREE(snapFile);
2427
    virObjectUnref(cfg);
2428 2429 2430 2431 2432 2433 2434 2435 2436
    return ret;
}

/* Hash iterator callback to discard multiple snapshots.  */
void qemuDomainSnapshotDiscardAll(void *payload,
                                  const void *name ATTRIBUTE_UNUSED,
                                  void *data)
{
    virDomainSnapshotObjPtr snap = payload;
2437
    virQEMUSnapRemovePtr curr = data;
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
    int err;

    if (snap->def->current)
        curr->current = true;
    err = qemuDomainSnapshotDiscard(curr->driver, curr->vm, snap, false,
                                    curr->metadata_only);
    if (err && !curr->err)
        curr->err = err;
}

int
2449
qemuDomainSnapshotDiscardAllMetadata(virQEMUDriverPtr driver,
2450 2451
                                     virDomainObjPtr vm)
{
2452
    virQEMUSnapRemove rem;
2453 2454 2455 2456 2457

    rem.driver = driver;
    rem.vm = vm;
    rem.metadata_only = true;
    rem.err = 0;
2458 2459
    virDomainSnapshotForEach(vm->snapshots, qemuDomainSnapshotDiscardAll,
                             &rem);
2460 2461 2462 2463 2464

    return rem.err;
}

/*
2465
 * The caller must hold a lock the vm.
2466 2467
 */
void
2468
qemuDomainRemoveInactive(virQEMUDriverPtr driver,
2469 2470
                         virDomainObjPtr vm)
{
2471
    bool haveJob = true;
2472
    char *snapDir;
2473
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2474

2475 2476 2477
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        haveJob = false;

2478 2479 2480 2481 2482
    /* Remove any snapshot metadata prior to removing the domain */
    if (qemuDomainSnapshotDiscardAllMetadata(driver, vm) < 0) {
        VIR_WARN("unable to remove all snapshots for domain %s",
                 vm->def->name);
    }
2483
    else if (virAsprintf(&snapDir, "%s/%s", cfg->snapshotDir,
2484 2485
                         vm->def->name) < 0) {
        VIR_WARN("unable to remove snapshot directory %s/%s",
2486
                 cfg->snapshotDir, vm->def->name);
2487 2488 2489 2490 2491
    } else {
        if (rmdir(snapDir) < 0 && errno != ENOENT)
            VIR_WARN("unable to remove snapshot directory %s", snapDir);
        VIR_FREE(snapDir);
    }
2492
    virDomainObjListRemove(driver->domains, vm);
2493
    virObjectUnref(cfg);
2494 2495

    if (haveJob)
2496
        qemuDomainObjEndJob(driver, vm);
2497
}
2498 2499

void
2500
qemuDomainSetFakeReboot(virQEMUDriverPtr driver,
2501 2502 2503 2504
                        virDomainObjPtr vm,
                        bool value)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2505
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2506 2507

    if (priv->fakeReboot == value)
2508
        goto cleanup;
2509 2510 2511

    priv->fakeReboot = value;

2512
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
2513
        VIR_WARN("Failed to save status on vm %s", vm->def->name);
2514

2515
 cleanup:
2516
    virObjectUnref(cfg);
2517
}
M
Michal Privoznik 已提交
2518

2519 2520 2521
static int
qemuDomainCheckRemoveOptionalDisk(virQEMUDriverPtr driver,
                                  virDomainObjPtr vm,
2522
                                  size_t diskIndex)
2523 2524
{
    char uuid[VIR_UUID_STRING_BUFLEN];
2525
    virObjectEventPtr event = NULL;
2526
    virDomainDiskDefPtr disk = vm->def->disks[diskIndex];
2527
    const char *src = virDomainDiskGetSource(disk);
2528 2529 2530 2531 2532

    virUUIDFormat(vm->def->uuid, uuid);

    VIR_DEBUG("Dropping disk '%s' on domain '%s' (UUID '%s') "
              "due to inaccessible source '%s'",
2533
              disk->dst, vm->def->name, uuid, src);
2534 2535 2536 2537

    if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM ||
        disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {

2538
        event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
2539 2540
                                                   disk->info.alias,
                                                   VIR_DOMAIN_EVENT_DISK_CHANGE_MISSING_ON_START);
2541
        ignore_value(virDomainDiskSetSource(disk, NULL));
2542
    } else {
2543
        event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
2544 2545
                                                   disk->info.alias,
                                                   VIR_DOMAIN_EVENT_DISK_DROP_MISSING_ON_START);
2546 2547
        virDomainDiskRemove(vm->def, diskIndex);
        virDomainDiskDefFree(disk);
2548 2549 2550 2551 2552 2553 2554 2555
    }

    if (event)
        qemuDomainEventQueue(driver, event);

    return 0;
}

2556 2557 2558
static int
qemuDomainCheckDiskStartupPolicy(virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
2559
                                 size_t diskIndex,
2560 2561
                                 bool cold_boot)
{
2562
    int startupPolicy = vm->def->disks[diskIndex]->startupPolicy;
2563
    int device = vm->def->disks[diskIndex]->device;
2564

2565
    switch ((virDomainStartupPolicy) startupPolicy) {
2566
        case VIR_DOMAIN_STARTUP_POLICY_OPTIONAL:
2567 2568 2569 2570 2571 2572 2573
            /* Once started with an optional disk, qemu saves its section
             * in the migration stream, so later, when restoring from it
             * we must make sure the sections match. */
            if (!cold_boot &&
                device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
                device != VIR_DOMAIN_DISK_DEVICE_CDROM)
                goto error;
2574 2575 2576 2577 2578 2579
            break;

        case VIR_DOMAIN_STARTUP_POLICY_MANDATORY:
            goto error;

        case VIR_DOMAIN_STARTUP_POLICY_REQUISITE:
2580
            if (cold_boot)
2581 2582 2583 2584 2585 2586 2587 2588 2589
                goto error;
            break;

        case VIR_DOMAIN_STARTUP_POLICY_DEFAULT:
        case VIR_DOMAIN_STARTUP_POLICY_LAST:
            /* this should never happen */
            break;
    }

2590
    if (qemuDomainCheckRemoveOptionalDisk(driver, vm, diskIndex) < 0)
2591
        goto error;
2592 2593 2594

    return 0;

2595
 error:
2596 2597 2598
    return -1;
}

2599

M
Michal Privoznik 已提交
2600
int
2601
qemuDomainCheckDiskPresence(virQEMUDriverPtr driver,
M
Michal Privoznik 已提交
2602
                            virDomainObjPtr vm,
2603
                            bool cold_boot)
M
Michal Privoznik 已提交
2604 2605
{
    int ret = -1;
2606
    size_t i;
M
Michal Privoznik 已提交
2607

2608
    VIR_DEBUG("Checking for disk presence");
2609
    for (i = vm->def->ndisks; i > 0; i--) {
2610 2611
        size_t idx = i - 1;
        virDomainDiskDefPtr disk = vm->def->disks[idx];
2612
        virStorageFileFormat format = virDomainDiskGetFormat(disk);
M
Michal Privoznik 已提交
2613

2614
        if (virStorageSourceIsEmpty(disk->src))
2615 2616 2617 2618 2619
            continue;

        /* There is no need to check the backing chain for disks
         * without backing support, the fact that the file exists is
         * more than enough */
2620
        if (virStorageSourceIsLocalStorage(disk->src) &&
2621
            format >= VIR_STORAGE_FILE_NONE &&
2622
            format < VIR_STORAGE_FILE_BACKING &&
2623
            virFileExists(virDomainDiskGetSource(disk)))
M
Michal Privoznik 已提交
2624 2625
            continue;

2626
        if (qemuDomainDetermineDiskChain(driver, vm, disk, true, true) >= 0)
M
Michal Privoznik 已提交
2627
            continue;
2628

2629
        if (disk->startupPolicy &&
2630
            qemuDomainCheckDiskStartupPolicy(driver, vm, idx,
2631 2632 2633
                                             cold_boot) >= 0) {
            virResetLastError();
            continue;
M
Michal Privoznik 已提交
2634 2635
        }

2636
        goto error;
M
Michal Privoznik 已提交
2637 2638 2639 2640
    }

    ret = 0;

2641
 error:
M
Michal Privoznik 已提交
2642 2643
    return ret;
}
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653

/*
 * The vm must be locked when any of the following cleanup functions is
 * called.
 */
int
qemuDomainCleanupAdd(virDomainObjPtr vm,
                     qemuDomainCleanupCallback cb)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2654
    size_t i;
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664

    VIR_DEBUG("vm=%s, cb=%p", vm->def->name, cb);

    for (i = 0; i < priv->ncleanupCallbacks; i++) {
        if (priv->cleanupCallbacks[i] == cb)
            return 0;
    }

    if (VIR_RESIZE_N(priv->cleanupCallbacks,
                     priv->ncleanupCallbacks_max,
2665
                     priv->ncleanupCallbacks, 1) < 0)
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
        return -1;

    priv->cleanupCallbacks[priv->ncleanupCallbacks++] = cb;
    return 0;
}

void
qemuDomainCleanupRemove(virDomainObjPtr vm,
                        qemuDomainCleanupCallback cb)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2677
    size_t i;
2678 2679 2680 2681

    VIR_DEBUG("vm=%s, cb=%p", vm->def->name, cb);

    for (i = 0; i < priv->ncleanupCallbacks; i++) {
2682 2683 2684
        if (priv->cleanupCallbacks[i] == cb)
            VIR_DELETE_ELEMENT_INPLACE(priv->cleanupCallbacks,
                                       i, priv->ncleanupCallbacks);
2685 2686 2687 2688 2689 2690 2691 2692
    }

    VIR_SHRINK_N(priv->cleanupCallbacks,
                 priv->ncleanupCallbacks_max,
                 priv->ncleanupCallbacks_max - priv->ncleanupCallbacks);
}

void
2693
qemuDomainCleanupRun(virQEMUDriverPtr driver,
2694 2695 2696
                     virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2697
    size_t i;
2698 2699 2700 2701

    VIR_DEBUG("driver=%p, vm=%s", driver, vm->def->name);

    /* run cleanup callbacks in reverse order */
2702 2703
    for (i = 0; i < priv->ncleanupCallbacks; i++) {
        if (priv->cleanupCallbacks[priv->ncleanupCallbacks - (i + 1)])
2704 2705 2706 2707 2708 2709 2710
            priv->cleanupCallbacks[i](driver, vm);
    }

    VIR_FREE(priv->cleanupCallbacks);
    priv->ncleanupCallbacks = 0;
    priv->ncleanupCallbacks_max = 0;
}
2711

2712 2713 2714
static void
qemuDomainGetImageIds(virQEMUDriverConfigPtr cfg,
                      virDomainObjPtr vm,
2715
                      virStorageSourcePtr src,
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
                      uid_t *uid, gid_t *gid)
{
    virSecurityLabelDefPtr vmlabel;
    virSecurityDeviceLabelDefPtr disklabel;

    if (uid)
        *uid = -1;
    if (gid)
        *gid = -1;

    if (cfg) {
        if (uid)
            *uid = cfg->user;

        if (gid)
            *gid = cfg->group;
    }

2734 2735
    if (vm && (vmlabel = virDomainDefGetSecurityLabelDef(vm->def, "dac")) &&
        vmlabel->label)
2736 2737
        virParseOwnershipIds(vmlabel->label, uid, gid);

2738
    if ((disklabel = virStorageSourceGetSecurityLabelDef(src, "dac")) &&
2739
        disklabel->label)
2740 2741 2742 2743
        virParseOwnershipIds(disklabel->label, uid, gid);
}


2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
int
qemuDomainStorageFileInit(virQEMUDriverPtr driver,
                          virDomainObjPtr vm,
                          virStorageSourcePtr src)
{
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    uid_t uid;
    gid_t gid;
    int ret = -1;

    qemuDomainGetImageIds(cfg, vm, src, &uid, &gid);

    if (virStorageFileInitAs(src, uid, gid) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    virObjectUnref(cfg);
    return ret;
}


2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
char *
qemuDomainStorageAlias(const char *device, int depth)
{
    char *alias;

    if (STRPREFIX(device, QEMU_DRIVE_HOST_PREFIX))
        device += strlen(QEMU_DRIVE_HOST_PREFIX);

    if (!depth)
        ignore_value(VIR_STRDUP(alias, device));
    else
        ignore_value(virAsprintf(&alias, "%s.%d", device, depth));
    return alias;
}


2783
int
2784
qemuDomainDetermineDiskChain(virQEMUDriverPtr driver,
2785
                             virDomainObjPtr vm,
2786
                             virDomainDiskDefPtr disk,
2787 2788
                             bool force_probe,
                             bool report_broken)
2789
{
2790 2791
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    int ret = 0;
2792 2793
    uid_t uid;
    gid_t gid;
2794

2795
    if (virStorageSourceIsEmpty(disk->src))
2796
        goto cleanup;
2797

2798
    if (disk->src->backingStore) {
2799
        if (force_probe)
2800
            virStorageSourceBackingStoreClear(disk->src);
2801
        else
2802
            goto cleanup;
2803
    }
2804

2805
    qemuDomainGetImageIds(cfg, vm, disk->src, &uid, &gid);
2806

2807
    if (virStorageFileGetMetadata(disk->src,
2808
                                  uid, gid,
2809
                                  cfg->allowDiskFormatProbing,
2810
                                  report_broken) < 0)
2811 2812
        ret = -1;

2813
 cleanup:
2814 2815
    virObjectUnref(cfg);
    return ret;
2816
}
2817

2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840

bool
qemuDomainDiskBlockJobIsActive(virDomainDiskDefPtr disk)
{
    if (disk->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' already in active block job"),
                       disk->dst);

        return true;
    }

    if (disk->blockjob) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("disk '%s' already in active block job"),
                       disk->dst);
        return true;
    }

    return false;
}


2841 2842
int
qemuDomainUpdateDeviceList(virQEMUDriverPtr driver,
2843 2844
                           virDomainObjPtr vm,
                           int asyncJob)
2845 2846 2847
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char **aliases;
2848
    int rc;
2849 2850 2851 2852

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE_DEL_EVENT))
        return 0;

2853 2854
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;
2855 2856 2857 2858
    rc = qemuMonitorGetDeviceAliases(priv->mon, &aliases);
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return -1;
    if (rc < 0)
2859 2860 2861 2862 2863 2864
        return -1;

    virStringFreeList(priv->qemuDevices);
    priv->qemuDevices = aliases;
    return 0;
}
2865

2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 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

int
qemuDomainUpdateMemoryDeviceInfo(virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
                                 int asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virHashTablePtr meminfo = NULL;
    int rc;
    size_t i;

    if (vm->def->nmems == 0)
        return 0;

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

    rc = qemuMonitorGetMemoryDeviceInfo(priv->mon, &meminfo);

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

    /* if qemu doesn't support the info request, just carry on */
    if (rc == -2)
        return 0;

    if (rc < 0)
        return -1;

    for (i = 0; i < vm->def->nmems; i++) {
        virDomainMemoryDefPtr mem = vm->def->mems[i];
        qemuMonitorMemoryDeviceInfoPtr dimm;

        if (!mem->info.alias)
            continue;

        if (!(dimm = virHashLookup(meminfo, mem->info.alias)))
            continue;

        mem->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM;
        mem->info.addr.dimm.slot = dimm->slot;
        mem->info.addr.dimm.base = dimm->address;
    }

    virHashFree(meminfo);
    return 0;
}


2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
bool
qemuDomainDefCheckABIStability(virQEMUDriverPtr driver,
                               virDomainDefPtr src,
                               virDomainDefPtr dst)
{
    virDomainDefPtr migratableDefSrc = NULL;
    virDomainDefPtr migratableDefDst = NULL;
    const int flags = VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_UPDATE_CPU | VIR_DOMAIN_XML_MIGRATABLE;
    bool ret = false;

    if (!(migratableDefSrc = qemuDomainDefCopy(driver, src, flags)) ||
        !(migratableDefDst = qemuDomainDefCopy(driver, dst, flags)))
        goto cleanup;

    ret = virDomainDefCheckABIStability(migratableDefSrc, migratableDefDst);

2931
 cleanup:
2932 2933 2934 2935
    virDomainDefFree(migratableDefSrc);
    virDomainDefFree(migratableDefDst);
    return ret;
}
2936 2937

bool
2938
qemuDomainAgentAvailable(virDomainObjPtr vm,
2939 2940
                         bool reportError)
{
2941 2942
    qemuDomainObjPrivatePtr priv = vm->privateData;

2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
    if (priv->agentError) {
        if (reportError) {
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                           _("QEMU guest agent is not "
                             "available due to an error"));
        }
        return false;
    }
    if (!priv->agent) {
        if (reportError) {
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
        }
        return false;
    }
2958 2959 2960 2961 2962 2963 2964
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_RUNNING) {
        if (reportError) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain is not running"));
        }
        return false;
    }
2965 2966
    return true;
}
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985

/*
 * Finish working with a domain object in an API.  This function
 * clears whatever was left of a domain that was gathered using
 * qemuDomObjFromDomain().  Currently that means only unlocking and
 * decrementing the reference counter of that domain.  And in order to
 * make sure the caller does not access the domain, the pointer is
 * cleared.
 */
void
qemuDomObjEndAPI(virDomainObjPtr *vm)
{
    if (!*vm)
        return;

    virObjectUnlock(*vm);
    virObjectUnref(*vm);
    *vm = NULL;
}
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004


int
qemuDomainAlignMemorySizes(virDomainDefPtr def)
{
    unsigned long long mem;
    size_t ncells = virDomainNumaGetNodeCount(def->numa);
    size_t i;

    /* align NUMA cell sizes if relevant */
    for (i = 0; i < ncells; i++) {
        mem = virDomainNumaGetNodeMemorySize(def->numa, i);
        virDomainNumaSetNodeMemorySize(def->numa, i, VIR_ROUND_UP(mem, 1024));
    }

    /* align initial memory size */
    mem = virDomainDefGetMemoryInitial(def);
    virDomainDefSetMemoryInitial(def, VIR_ROUND_UP(mem, 1024));

3005 3006 3007 3008
    /* Align maximum memory size. QEMU requires rounding to next 4KiB block.
     * We'll take the "traditional" path and round it to 1MiB*/
    def->mem.max_memory = VIR_ROUND_UP(def->mem.max_memory, 1024);

3009 3010 3011 3012
    /* Align memory module sizes */
    for (i = 0; i < def->nmems; i++)
        qemuDomainMemoryDeviceAlignSize(def->mems[i]);

3013 3014
    return 0;
}
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029


/**
 * qemuDomainMemoryDeviceAlignSize:
 * @mem: memory device definition object
 *
 * Aligns the size of the memory module as qemu enforces it. The size is updated
 * inplace. Default rounding is now to 1 MiB (qemu requires rouding to page,
 * size so this should be safe).
 */
void
qemuDomainMemoryDeviceAlignSize(virDomainMemoryDefPtr mem)
{
    mem->size = VIR_ROUND_UP(mem->size, 1024);
}