You need to sign in or sign up before continuing.
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
    virDomainChrSourceDefFree(priv->monConfig);
440
    qemuDomainObjFreeJob(priv);
441
    VIR_FREE(priv->vcpupids);
442
    VIR_FREE(priv->iothreadpids);
443
    VIR_FREE(priv->lockState);
J
Jiri Denemark 已提交
444
    VIR_FREE(priv->origname);
445

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

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


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

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

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


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

503 504 505 506 507 508 509 510 511 512 513 514
    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");
    }

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

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

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

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

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

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

564 565 566
    return 0;
}

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

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

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

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

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

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

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

621
        for (i = 0; i < n; i++) {
622 623 624 625 626 627 628 629 630 631 632 633
            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);
    }
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

    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);
    }
657

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

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

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

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

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

        if ((type = qemuDomainJobTypeFromString(tmp)) < 0) {
692 693
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown job type %s"), tmp);
694 695 696 697 698 699 700 701 702 703 704
            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) {
705 706
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown async job type %s"), tmp);
707 708 709 710 711
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
        priv->job.asyncJob = async;
J
Jiri Denemark 已提交
712 713 714 715

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

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

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    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);

748 749
    return 0;

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


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


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

774
    qemuDomainCmdlineDefFree(cmd);
775 776 777
}

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

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

796
    if (VIR_ALLOC(cmd) < 0)
797 798 799 800 801 802
        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 已提交
803
    uses_qemu_ns |= n > 0;
804 805

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

    for (i = 0; i < n; i++) {
        cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
        if (cmd->args[cmd->num_args] == NULL) {
811 812
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu command-line argument specified"));
813 814 815 816 817 818 819 820 821 822 823
            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 已提交
824
    uses_qemu_ns |= n > 0;
825 826

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

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

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

        tmp = virXMLPropString(nodes[i], "name");
        if (tmp == NULL) {
837 838
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu environment name specified"));
839 840 841
            goto error;
        }
        if (tmp[0] == '\0') {
842 843
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Empty qemu environment name specified"));
844 845 846
            goto error;
        }
        if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
847 848
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must begin with a letter or underscore"));
849 850 851
            goto error;
        }
        if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
852 853
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
854 855 856 857 858 859 860 861 862 863 864 865
            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 已提交
866 867 868 869
    if (uses_qemu_ns)
        *data = cmd;
    else
        VIR_FREE(cmd);
870 871 872

    return 0;

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

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

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

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

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

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

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


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

921

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

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

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

946 947 948 949 950 951
    /* 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 已提交
952
        if (STREQ(def->os.machine, "isapc")) {
953
            addDefaultUSB = false;
954
            break;
955
        }
L
Laine Stump 已提交
956 957 958 959
        if (STRPREFIX(def->os.machine, "pc-q35") ||
            STREQ(def->os.machine, "q35")) {
           addPCIeRoot = true;
           addDefaultUSB = false;
960
           addImplicitSATA = true;
L
Laine Stump 已提交
961 962
           break;
        }
963 964
        if (!STRPREFIX(def->os.machine, "pc-0.") &&
            !STRPREFIX(def->os.machine, "pc-1.") &&
965
            !STRPREFIX(def->os.machine, "pc-i440") &&
966 967 968 969 970 971
            !STREQ(def->os.machine, "pc") &&
            !STRPREFIX(def->os.machine, "rhel"))
            break;
        addPCIRoot = true;
        break;

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

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

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

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

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

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

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    /* 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 已提交
1035
        return -1;
1036 1037
        }
    }
1038

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

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

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    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;

1062 1063 1064
    return 0;
}

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

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

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

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

    return "rtl8139";
}
1086

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

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

1105 1106 1107 1108 1109 1110 1111 1112 1113
    /* 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 */
1114
                if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
E
Eric Blake 已提交
1115 1116
                    (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                     virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
1117
                    virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_AUTO);
1118 1119 1120

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

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

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

1143 1144 1145 1146
    /* 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 &&
1147
        ARCH_IS_S390(def->os.arch))
1148 1149
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO;

1150 1151 1152 1153 1154
    /* 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 &&
1155
        ARCH_IS_S390(def->os.arch))
1156 1157
        dev->data.controller->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE;

1158 1159 1160 1161 1162 1163 1164
    /* 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;

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    /* 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,
1176
                        dev->data.chr->target.name) < 0)
1177
            goto cleanup;
1178 1179 1180
        dev->data.chr->source.data.nix.listen = true;
    }

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    /* 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;
    }

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
    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 {
1206
            dev->data.video->vgamem = QEMU_QXL_VGAMEM_DEFAULT;
1207 1208 1209
        }
    }

1210 1211 1212 1213 1214
    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 "));
1215
        goto cleanup;
1216
    }
1217

1218 1219
    ret = 0;

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


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


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

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

1242
    virObjectUnref(cfg);
1243 1244
}

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

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

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

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

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

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

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

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

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

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

1294 1295 1296 1297 1298 1299 1300 1301 1302
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()) {
1303
        VIR_WARN("'%s' async job is owned by thread %llu",
1304 1305 1306 1307 1308 1309
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }
    priv->job.asyncOwner = 0;
}

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

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

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

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

1344 1345 1346 1347 1348 1349
    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);

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

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

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

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

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

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

1381
    qemuDomainObjResetJob(priv);
1382

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

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

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

1411
    virObjectUnref(cfg);
1412
    return 0;
1413

1414
 error:
J
Jiri Denemark 已提交
1415 1416 1417 1418 1419 1420
    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;

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

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

1438 1439
    ret = -1;
    if (errno == ETIMEDOUT) {
1440 1441 1442 1443 1444 1445 1446 1447
        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"));
        }
1448 1449 1450
        ret = -2;
    } else if (cfg->maxQueuedJobs &&
               priv->jobs_queued > cfg->maxQueuedJobs) {
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
        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"));
        }
1461 1462
        ret = -2;
    } else {
1463
        virReportSystemError(errno, "%s", _("cannot acquire job mutex"));
1464
    }
J
Jiri Denemark 已提交
1465 1466

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

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

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

1502
static int ATTRIBUTE_RETURN_CHECK
1503 1504
qemuDomainObjBeginNestedJob(virQEMUDriverPtr driver,
                            virDomainObjPtr obj,
1505
                            qemuDomainAsyncJob asyncJob)
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
{
    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()) {
1516
        VIR_WARN("This thread doesn't seem to be the async job owner: %llu",
1517 1518 1519 1520 1521 1522 1523 1524
                 priv->job.asyncOwner);
    }

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

1525

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

1538 1539
    priv->jobs_queued--;

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

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

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

1556 1557
    priv->jobs_queued--;

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

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

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

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

    priv->job.asyncAbort = true;
}

1579 1580 1581 1582 1583 1584 1585 1586 1587
/*
 * 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
 */
1588
static int
1589
qemuDomainObjEnterMonitorInternal(virQEMUDriverPtr driver,
1590
                                  virDomainObjPtr obj,
1591
                                  qemuDomainAsyncJob asyncJob)
1592 1593 1594
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1595
    if (asyncJob != QEMU_ASYNC_JOB_NONE) {
1596 1597 1598
        int ret;
        if ((ret = qemuDomainObjBeginNestedJob(driver, obj, asyncJob)) < 0)
            return ret;
1599
        if (!virDomainObjIsActive(obj)) {
1600 1601
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
1602
            qemuDomainObjEndJob(driver, obj);
1603 1604
            return -1;
        }
1605 1606 1607
    } 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");
1608 1609
    }

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

    return 0;
1618 1619
}

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

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

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

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

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

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

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

1654
/* obj must NOT be locked before calling
1655 1656
 *
 * Should be paired with an earlier qemuDomainObjEnterMonitor() call
1657 1658 1659 1660 1661 1662
 *
 * 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.
1663
 */
1664 1665
int qemuDomainObjExitMonitor(virQEMUDriverPtr driver,
                             virDomainObjPtr obj)
1666
{
1667
    qemuDomainObjExitMonitorInternal(driver, obj);
1668
    if (!virDomainObjIsActive(obj)) {
1669 1670 1671
        if (!virGetLastError())
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
1672 1673 1674
        return -1;
    }
    return 0;
1675
}
1676 1677

/*
1678
 * obj must be locked before calling
1679 1680
 *
 * To be called immediately before any QEMU monitor API call.
1681
 * Must have already either called qemuDomainObjBeginJob()
1682 1683 1684 1685 1686
 * 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
1687 1688 1689
 * 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).
1690 1691
 */
int
1692
qemuDomainObjEnterMonitorAsync(virQEMUDriverPtr driver,
1693
                               virDomainObjPtr obj,
1694
                               qemuDomainAsyncJob asyncJob)
1695
{
1696
    return qemuDomainObjEnterMonitorInternal(driver, obj, asyncJob);
1697 1698
}

D
Daniel P. Berrange 已提交
1699 1700


1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
/*
 * 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 已提交
1712 1713 1714
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

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

1723 1724 1725 1726 1727 1728 1729

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

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

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

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

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

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

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


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

    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,
1783
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
1784 1785
        goto cleanup;

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

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

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

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

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

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

        /* 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);
1847
            toremove++;
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
        } 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 已提交
1866
            VIR_DEBUG("Removing default pci-root from domain '%s'"
1867
                      " for migration compatibility", def->name);
1868
            toremove++;
1869 1870 1871 1872
        } else {
            pci = NULL;
        }

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

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


1889 1890
    }

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

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

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

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

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

    return virBufferContentAndReset(&buf);
}

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

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

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

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

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

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

1957

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

1965 1966 1967 1968 1969 1970 1971 1972 1973
    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));
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987

        /* 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);
        }
1988 1989 1990 1991
    }
}


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

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

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

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

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

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

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

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

    virObjectUnref(cfg);
2029 2030 2031
}


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

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

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

    virObjectUnref(cfg);
2049 2050 2051
}


2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
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);
}


2066
void qemuDomainObjCheckNetTaint(virQEMUDriverPtr driver,
2067
                                virDomainObjPtr obj,
2068 2069
                                virDomainNetDefPtr net,
                                int logFD)
2070
{
2071 2072 2073 2074 2075 2076
    /* 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)
2077
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_SHELL_SCRIPTS, logFD);
2078
}
2079 2080 2081


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

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

2094 2095 2096 2097 2098 2099 2100 2101 2102
    /* 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 已提交
2103
    if ((fd = open(logfile, oflags, mode)) < 0) {
2104 2105 2106 2107 2108 2109 2110
        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);
2111 2112 2113 2114 2115 2116 2117
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }
    if (trunc &&
        ftruncate(fd, 0) < 0) {
        virReportSystemError(errno, _("failed to truncate %s"),
                             logfile);
2118 2119 2120 2121
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }

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


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

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

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


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

2157 2158 2159
    fd = qemuDomainOpenLogHelper(cfg, vm, O_RDONLY, 0);
    virObjectUnref(cfg);
    if (fd < 0)
2160 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
        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;
}


2186
int qemuDomainAppendLog(virQEMUDriverPtr driver,
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
                        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;

2202
    if (virVasprintf(&message, fmt, argptr) < 0)
2203 2204 2205 2206 2207 2208 2209 2210 2211
        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;

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

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

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

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

    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);
2245 2246 2247 2248
    newxml = virDomainSnapshotDefFormat(
        uuidstr, snapshot->def,
        virDomainDefFormatConvertXMLFlags(QEMU_DOMAIN_FORMAT_LIVE_FLAGS),
        1);
2249
    if (newxml == NULL)
2250 2251
        return -1;

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

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

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

2265
 cleanup:
2266 2267 2268 2269 2270 2271 2272 2273
    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.  */
2274
static int
2275
qemuDomainSnapshotForEachQcow2Raw(virQEMUDriverPtr driver,
2276 2277 2278 2279 2280
                                  virDomainDefPtr def,
                                  const char *name,
                                  const char *op,
                                  bool try_all,
                                  int ndisks)
2281 2282
{
    const char *qemuimgarg[] = { NULL, "snapshot", NULL, NULL, NULL, NULL };
2283
    size_t i;
2284 2285 2286 2287 2288 2289 2290 2291 2292
    bool skipped = false;

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

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

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

            if (format > 0 && format != VIR_STORAGE_FILE_QCOW2) {
2301 2302 2303 2304 2305
                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",
2306
                             def->disks[i]->dst);
2307 2308
                    skipped = true;
                    continue;
2309 2310 2311 2312 2313
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
2314
                }
2315 2316 2317 2318
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Disk device '%s' does not support"
                                 " snapshotting"),
                               def->disks[i]->dst);
2319 2320 2321
                return -1;
            }

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

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

    return skipped ? 1 : 0;
}

2344 2345 2346
/* 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
2347
qemuDomainSnapshotForEachQcow2(virQEMUDriverPtr driver,
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
                               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);
}

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

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

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

    if (snap == vm->current_snapshot) {
        if (update_current && snap->def->parent) {
2399
            parentsnap = virDomainSnapshotFindByName(vm->snapshots,
2400 2401 2402 2403 2404 2405 2406
                                                     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,
2407
                                                    cfg->snapshotDir) < 0) {
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
                    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);
2420
    virDomainSnapshotObjListRemove(vm->snapshots, snap);
2421 2422 2423

    ret = 0;

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

/* Hash iterator callback to discard multiple snapshots.  */
void qemuDomainSnapshotDiscardAll(void *payload,
                                  const void *name ATTRIBUTE_UNUSED,
                                  void *data)
{
    virDomainSnapshotObjPtr snap = payload;
2436
    virQEMUSnapRemovePtr curr = data;
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
    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
2448
qemuDomainSnapshotDiscardAllMetadata(virQEMUDriverPtr driver,
2449 2450
                                     virDomainObjPtr vm)
{
2451
    virQEMUSnapRemove rem;
2452 2453 2454 2455 2456

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

    return rem.err;
}

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

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

2477 2478 2479 2480 2481
    /* 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);
    }
2482
    else if (virAsprintf(&snapDir, "%s/%s", cfg->snapshotDir,
2483 2484
                         vm->def->name) < 0) {
        VIR_WARN("unable to remove snapshot directory %s/%s",
2485
                 cfg->snapshotDir, vm->def->name);
2486 2487 2488 2489 2490
    } else {
        if (rmdir(snapDir) < 0 && errno != ENOENT)
            VIR_WARN("unable to remove snapshot directory %s", snapDir);
        VIR_FREE(snapDir);
    }
2491
    virDomainObjListRemove(driver->domains, vm);
2492
    virObjectUnref(cfg);
2493 2494

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

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

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

    priv->fakeReboot = value;

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

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

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

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

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

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

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

    if (event)
        qemuDomainEventQueue(driver, event);

    return 0;
}

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

2564
    switch ((virDomainStartupPolicy) startupPolicy) {
2565
        case VIR_DOMAIN_STARTUP_POLICY_OPTIONAL:
2566 2567 2568 2569 2570 2571 2572
            /* 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;
2573 2574 2575 2576 2577 2578
            break;

        case VIR_DOMAIN_STARTUP_POLICY_MANDATORY:
            goto error;

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

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

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

    return 0;

2594
 error:
2595 2596 2597
    return -1;
}

2598

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

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

2613
        if (virStorageSourceIsEmpty(disk->src))
2614 2615 2616 2617 2618
            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 */
2619
        if (virStorageSourceIsLocalStorage(disk->src) &&
2620
            format >= VIR_STORAGE_FILE_NONE &&
2621
            format < VIR_STORAGE_FILE_BACKING &&
2622
            virFileExists(virDomainDiskGetSource(disk)))
M
Michal Privoznik 已提交
2623 2624
            continue;

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

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

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

    ret = 0;

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

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

    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,
2664
                     priv->ncleanupCallbacks, 1) < 0)
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
        return -1;

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

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

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

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

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

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

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

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

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

2711 2712 2713
static void
qemuDomainGetImageIds(virQEMUDriverConfigPtr cfg,
                      virDomainObjPtr vm,
2714
                      virStorageSourcePtr src,
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
                      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;
    }

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

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


2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
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;
}


2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
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;
}


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

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

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

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

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

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

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

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


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

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

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

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

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

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


2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
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);

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

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

2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
    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;
    }
2957 2958 2959 2960 2961 2962 2963
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_RUNNING) {
        if (reportError) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain is not running"));
        }
        return false;
    }
2964 2965
    return true;
}
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984

/*
 * 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;
}
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003


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));

3004 3005 3006 3007
    /* 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);

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

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


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