qemu_domain.c 108.7 KB
Newer Older
1
/*
2
 * qemu_domain.c: QEMU domain private state
3
 *
4
 * Copyright (C) 2006-2015 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 130
    if (event)
        virObjectEventStateQueue(driver->domainEventState, event);
131 132 133
}


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

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

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

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

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

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

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

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

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

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

    qemuDomainObjResetJob(priv);
    qemuDomainObjResetAsyncJob(priv);
}

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

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

210

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

    if (!jobInfo->started)
        return 0;

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

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

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

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
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 已提交
254 255 256 257
int
qemuDomainJobInfoToInfo(qemuDomainJobInfoPtr jobInfo,
                        virDomainJobInfoPtr info)
{
258
    info->type = jobInfo->type;
J
Jiri Denemark 已提交
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
    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;

293 294 295 296 297 298 299
    if (jobInfo->timeDeltaSet &&
        jobInfo->timeElapsed > jobInfo->timeDelta &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_TIME_ELAPSED_NET,
                                jobInfo->timeElapsed - jobInfo->timeDelta) < 0)
        goto error;

J
Jiri Denemark 已提交
300 301 302 303 304 305 306 307 308 309 310 311
    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;

312 313 314 315 316 317 318 319
    if (status->downtime_set &&
        jobInfo->timeDeltaSet &&
        status->downtime > jobInfo->timeDelta &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DOWNTIME_NET,
                                status->downtime - jobInfo->timeDelta) < 0)
        goto error;

320 321 322 323 324 325
    if (status->setup_time_set &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_SETUP_TIME,
                                status->setup_time) < 0)
        goto error;

J
Jiri Denemark 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    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;

351 352 353 354 355 356
    if (status->ram_bps &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_BPS,
                                status->ram_bps) < 0)
        goto error;

J
Jiri Denemark 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    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;

381 382 383 384 385 386
    if (status->disk_bps &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_BPS,
                                status->disk_bps) < 0)
        goto error;

J
Jiri Denemark 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    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;
}


417 418 419 420 421 422 423 424
static virClassPtr qemuDomainDiskPrivateClass;

static int
qemuDomainDiskPrivateOnceInit(void)
{
    qemuDomainDiskPrivateClass = virClassNew(virClassForObject(),
                                             "qemuDomainDiskPrivate",
                                             sizeof(qemuDomainDiskPrivate),
425
                                             NULL);
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    if (!qemuDomainDiskPrivateClass)
        return -1;
    else
        return 0;
}

VIR_ONCE_GLOBAL_INIT(qemuDomainDiskPrivate)

static virObjectPtr
qemuDomainDiskPrivateNew(void)
{
    qemuDomainDiskPrivatePtr priv;

    if (qemuDomainDiskPrivateInitialize() < 0)
        return NULL;

    if (!(priv = virObjectNew(qemuDomainDiskPrivateClass)))
        return NULL;

    return (virObjectPtr) priv;
}


449 450
static void *
qemuDomainObjPrivateAlloc(void)
451 452 453 454 455 456
{
    qemuDomainObjPrivatePtr priv;

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

457 458 459
    if (qemuDomainObjInitJob(priv) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to init qemu driver mutexes"));
460
        goto error;
461
    }
462

463 464 465
    if (virCondInit(&priv->unplugFinished) < 0)
        goto error;

466
    if (!(priv->devs = virChrdevAlloc()))
467 468
        goto error;

469
    priv->migMaxBandwidth = QEMU_DOMAIN_MIG_BANDWIDTH_MAX;
470

471
    return priv;
472

473
 error:
474 475
    VIR_FREE(priv);
    return NULL;
476 477
}

478 479
static void
qemuDomainObjPrivateFree(void *data)
480 481 482
{
    qemuDomainObjPrivatePtr priv = data;

483
    virObjectUnref(priv->qemuCaps);
484

485
    virCgroupFree(&priv->cgroup);
486
    virDomainPCIAddressSetFree(priv->pciaddrs);
J
Ján Tomko 已提交
487
    virDomainCCWAddressSetFree(priv->ccwaddrs);
488
    virDomainVirtioSerialAddrSetFree(priv->vioserialaddrs);
489
    virDomainChrSourceDefFree(priv->monConfig);
490
    qemuDomainObjFreeJob(priv);
491
    VIR_FREE(priv->vcpupids);
492
    VIR_FREE(priv->lockState);
J
Jiri Denemark 已提交
493
    VIR_FREE(priv->origname);
494

495
    virCondDestroy(&priv->unplugFinished);
496
    virStringFreeList(priv->qemuDevices);
497
    virChrdevFree(priv->devs);
498

499 500
    /* This should never be non-NULL if we get here, but just in case... */
    if (priv->mon) {
501
        VIR_ERROR(_("Unexpected QEMU monitor still active during domain deletion"));
502 503
        qemuMonitorClose(priv->mon);
    }
D
Daniel P. Berrange 已提交
504 505 506 507
    if (priv->agent) {
        VIR_ERROR(_("Unexpected QEMU agent still active during domain deletion"));
        qemuAgentClose(priv->agent);
    }
508
    VIR_FREE(priv->cleanupCallbacks);
509
    virBitmapFree(priv->autoNodeset);
510
    virBitmapFree(priv->autoCpuset);
511 512 513 514
    VIR_FREE(priv);
}


515
static int
516 517
qemuDomainObjPrivateXMLFormat(virBufferPtr buf,
                              virDomainObjPtr vm)
518
{
519
    qemuDomainObjPrivatePtr priv = vm->privateData;
520
    const char *monitorpath;
521
    qemuDomainJob job;
522 523 524

    /* priv->monitor_chr is set only for qemu */
    if (priv->monConfig) {
525
        switch (priv->monConfig->type) {
526
        case VIR_DOMAIN_CHR_TYPE_UNIX:
527
            monitorpath = priv->monConfig->data.nix.path;
528 529 530
            break;
        default:
        case VIR_DOMAIN_CHR_TYPE_PTY:
531
            monitorpath = priv->monConfig->data.file.path;
532 533 534
            break;
        }

535
        virBufferEscapeString(buf, "<monitor path='%s'", monitorpath);
536 537
        if (priv->monJSON)
            virBufferAddLit(buf, " json='1'");
538
        virBufferAsprintf(buf, " type='%s'/>\n",
539
                          virDomainChrTypeToString(priv->monConfig->type));
540 541 542 543
    }


    if (priv->nvcpupids) {
544
        size_t i;
545 546
        virBufferAddLit(buf, "<vcpus>\n");
        virBufferAdjustIndent(buf, 2);
547
        for (i = 0; i < priv->nvcpupids; i++)
548 549 550
            virBufferAsprintf(buf, "<vcpu pid='%d'/>\n", priv->vcpupids[i]);
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</vcpus>\n");
551 552
    }

553
    if (priv->qemuCaps) {
554
        size_t i;
555 556
        virBufferAddLit(buf, "<qemuCaps>\n");
        virBufferAdjustIndent(buf, 2);
557
        for (i = 0; i < QEMU_CAPS_LAST; i++) {
558
            if (virQEMUCapsGet(priv->qemuCaps, i)) {
559
                virBufferAsprintf(buf, "<flag name='%s'/>\n",
560
                                  virQEMUCapsTypeToString(i));
561 562
            }
        }
563 564
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</qemuCaps>\n");
565 566
    }

567
    if (priv->lockState)
568
        virBufferAsprintf(buf, "<lockstate>%s</lockstate>\n", priv->lockState);
569

570 571 572 573
    job = priv->job.active;
    if (!qemuDomainTrackJob(job))
        priv->job.active = QEMU_JOB_NONE;

574
    if (priv->job.active || priv->job.asyncJob) {
575
        virBufferAsprintf(buf, "<job type='%s' async='%s'",
576 577
                          qemuDomainJobTypeToString(priv->job.active),
                          qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
J
Jiri Denemark 已提交
578 579 580 581 582
        if (priv->job.phase) {
            virBufferAsprintf(buf, " phase='%s'",
                              qemuDomainAsyncJobPhaseToString(
                                    priv->job.asyncJob, priv->job.phase));
        }
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
            virBufferAddLit(buf, "/>\n");
        } else {
            size_t i;
            virDomainDiskDefPtr disk;
            qemuDomainDiskPrivatePtr diskPriv;

            virBufferAddLit(buf, ">\n");
            virBufferAdjustIndent(buf, 2);

            for (i = 0; i < vm->def->ndisks; i++) {
                disk = vm->def->disks[i];
                diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
                virBufferAsprintf(buf, "<disk dev='%s' migrating='%s'/>\n",
                                  disk->dst,
                                  diskPriv->migrating ? "yes" : "no");
            }

            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</job>\n");
        }
604
    }
605
    priv->job.active = job;
606

607
    if (priv->fakeReboot)
608
        virBufferAddLit(buf, "<fakereboot/>\n");
609

610 611
    if (priv->qemuDevices && *priv->qemuDevices) {
        char **tmp = priv->qemuDevices;
612 613
        virBufferAddLit(buf, "<devices>\n");
        virBufferAdjustIndent(buf, 2);
614
        while (*tmp) {
615
            virBufferAsprintf(buf, "<device alias='%s'/>\n", *tmp);
616 617
            tmp++;
        }
618 619
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</devices>\n");
620 621
    }

622 623 624 625 626 627 628 629 630 631
    if (priv->autoNodeset) {
        char *nodeset = virBitmapFormat(priv->autoNodeset);

        if (!nodeset)
            return -1;

        virBufferAsprintf(buf, "<numad nodeset='%s'/>\n", nodeset);
        VIR_FREE(nodeset);
    }

632 633 634
    return 0;
}

635
static int
636
qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt,
637
                             virDomainObjPtr vm,
638
                             virDomainDefParserConfigPtr config)
639
{
640
    qemuDomainObjPrivatePtr priv = vm->privateData;
641
    virQEMUDriverPtr driver = config->priv;
642
    char *monitorpath;
643
    char *tmp = NULL;
644 645
    int n;
    size_t i;
646
    xmlNodePtr *nodes = NULL;
647
    virQEMUCapsPtr qemuCaps = NULL;
648
    virCapsPtr caps = NULL;
649

650
    if (VIR_ALLOC(priv->monConfig) < 0)
651 652 653 654
        goto error;

    if (!(monitorpath =
          virXPathString("string(./monitor[1]/@path)", ctxt))) {
655 656
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no monitor path"));
657 658 659 660 661
        goto error;
    }

    tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
    if (tmp)
662
        priv->monConfig->type = virDomainChrTypeFromString(tmp);
663
    else
664
        priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
665 666
    VIR_FREE(tmp);

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

670
    switch (priv->monConfig->type) {
671
    case VIR_DOMAIN_CHR_TYPE_PTY:
672
        priv->monConfig->data.file.path = monitorpath;
673 674
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
675
        priv->monConfig->data.nix.path = monitorpath;
676 677 678
        break;
    default:
        VIR_FREE(monitorpath);
679 680 681
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported monitor type '%s'"),
                       virDomainChrTypeToString(priv->monConfig->type));
682 683 684 685 686 687 688 689
        goto error;
    }

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

693
        for (i = 0; i < n; i++) {
694 695 696 697 698 699 700 701 702 703 704 705
            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);
    }
706

707
    if ((n = virXPathNodeSet("./qemuCaps/flag", ctxt, &nodes)) < 0) {
708 709
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to parse qemu capabilities flags"));
710 711 712
        goto error;
    }
    if (n > 0) {
713
        if (!(qemuCaps = virQEMUCapsNew()))
714 715
            goto error;

716
        for (i = 0; i < n; i++) {
717 718
            char *str = virXMLPropString(nodes[i], "name");
            if (str) {
719
                int flag = virQEMUCapsTypeFromString(str);
720
                if (flag < 0) {
721 722
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unknown qemu capabilities flag %s"), str);
723
                    VIR_FREE(str);
724 725
                    goto error;
                }
726
                VIR_FREE(str);
727
                virQEMUCapsSet(qemuCaps, flag);
728 729 730
            }
        }

731
        priv->qemuCaps = qemuCaps;
732
        qemuCaps = NULL;
733 734 735
    }
    VIR_FREE(nodes);

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

738 739 740 741
    if ((tmp = virXPathString("string(./job[1]/@type)", ctxt))) {
        int type;

        if ((type = qemuDomainJobTypeFromString(tmp)) < 0) {
742 743
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown job type %s"), tmp);
744 745 746 747 748 749 750 751 752 753 754
            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) {
755 756
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown async job type %s"), tmp);
757 758 759 760 761
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
        priv->job.asyncJob = async;
J
Jiri Denemark 已提交
762 763 764 765

        if ((tmp = virXPathString("string(./job[1]/@phase)", ctxt))) {
            priv->job.phase = qemuDomainAsyncJobPhaseFromString(async, tmp);
            if (priv->job.phase < 0) {
766 767
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unknown job phase %s"), tmp);
J
Jiri Denemark 已提交
768 769 770 771 772
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        }
773 774
    }

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    if ((n = virXPathNodeSet("./job[1]/disk[@migrating='yes']",
                             ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to parse list of disks marked for migration"));
        goto error;
    }
    if (n > 0) {
        if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
            VIR_WARN("Found disks marked for migration but we were not "
                     "migrating");
            n = 0;
        }
        for (i = 0; i < n; i++) {
            char *dst = virXMLPropString(nodes[i], "dev");
            virDomainDiskDefPtr disk;

            if (dst && (disk = virDomainDiskByName(vm->def, dst, false)))
                QEMU_DOMAIN_DISK_PRIVATE(disk)->migrating = true;
            VIR_FREE(dst);
        }
    }
    VIR_FREE(nodes);

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

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    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);

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto error;

    if ((tmp = virXPathString("string(./numad/@nodeset)", ctxt))) {
        if (virBitmapParse(tmp, 0, &priv->autoNodeset,
                           caps->host.nnumaCell_max) < 0)
            goto error;

        if (!(priv->autoCpuset = virCapabilitiesGetCpusForNodemask(caps,
                                                                   priv->autoNodeset)))
            goto error;
    }
    virObjectUnref(caps);
    caps = NULL;
    VIR_FREE(tmp);

837 838
    return 0;

839
 error:
840
    virDomainChrSourceDefFree(priv->monConfig);
841 842
    priv->monConfig = NULL;
    VIR_FREE(nodes);
843
    VIR_FREE(tmp);
844 845
    virStringFreeList(priv->qemuDevices);
    priv->qemuDevices = NULL;
846
    virObjectUnref(qemuCaps);
847
    virObjectUnref(caps);
848 849 850 851
    return -1;
}


852 853 854
virDomainXMLPrivateDataCallbacks virQEMUDriverPrivateDataCallbacks = {
    .alloc = qemuDomainObjPrivateAlloc,
    .free = qemuDomainObjPrivateFree,
855
    .diskNew = qemuDomainDiskPrivateNew,
856 857 858 859 860
    .parse = qemuDomainObjPrivateXMLParse,
    .format = qemuDomainObjPrivateXMLFormat,
};


861 862 863 864 865
static void
qemuDomainDefNamespaceFree(void *nsdata)
{
    qemuDomainCmdlineDefPtr cmd = nsdata;

866
    qemuDomainCmdlineDefFree(cmd);
867 868 869
}

static int
P
Philipp Hahn 已提交
870 871
qemuDomainDefNamespaceParse(xmlDocPtr xml ATTRIBUTE_UNUSED,
                            xmlNodePtr root ATTRIBUTE_UNUSED,
872 873 874 875
                            xmlXPathContextPtr ctxt,
                            void **data)
{
    qemuDomainCmdlineDefPtr cmd = NULL;
P
Philipp Hahn 已提交
876
    bool uses_qemu_ns = false;
877
    xmlNodePtr *nodes = NULL;
878 879
    int n;
    size_t i;
880

P
Philipp Hahn 已提交
881
    if (xmlXPathRegisterNs(ctxt, BAD_CAST "qemu", BAD_CAST QEMU_NAMESPACE_HREF) < 0) {
882 883 884
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to register xml namespace '%s'"),
                       QEMU_NAMESPACE_HREF);
885 886 887
        return -1;
    }

888
    if (VIR_ALLOC(cmd) < 0)
889 890 891 892 893 894
        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 已提交
895
    uses_qemu_ns |= n > 0;
896 897

    if (n && VIR_ALLOC_N(cmd->args, n) < 0)
898
        goto error;
899 900 901 902

    for (i = 0; i < n; i++) {
        cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
        if (cmd->args[cmd->num_args] == NULL) {
903 904
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu command-line argument specified"));
905 906 907 908 909 910 911 912 913 914 915
            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 已提交
916
    uses_qemu_ns |= n > 0;
917 918

    if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
919
        goto error;
920 921

    if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
922
        goto error;
923 924 925 926 927 928

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

        tmp = virXMLPropString(nodes[i], "name");
        if (tmp == NULL) {
929 930
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu environment name specified"));
931 932 933
            goto error;
        }
        if (tmp[0] == '\0') {
934 935
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Empty qemu environment name specified"));
936 937 938
            goto error;
        }
        if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
939 940
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must begin with a letter or underscore"));
941 942 943
            goto error;
        }
        if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
944 945
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
946 947 948 949 950 951 952 953 954 955 956 957
            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 已提交
958 959 960 961
    if (uses_qemu_ns)
        *data = cmd;
    else
        VIR_FREE(cmd);
962 963 964

    return 0;

965
 error:
966 967 968 969 970 971 972 973 974 975
    VIR_FREE(nodes);
    qemuDomainDefNamespaceFree(cmd);
    return -1;
}

static int
qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
                                void *nsdata)
{
    qemuDomainCmdlineDefPtr cmd = nsdata;
976
    size_t i;
977 978 979 980

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

981 982 983
    virBufferAddLit(buf, "<qemu:commandline>\n");
    virBufferAdjustIndent(buf, 2);

984
    for (i = 0; i < cmd->num_args; i++)
985
        virBufferEscapeString(buf, "<qemu:arg value='%s'/>\n",
986 987
                              cmd->args[i]);
    for (i = 0; i < cmd->num_env; i++) {
988
        virBufferAsprintf(buf, "<qemu:env name='%s'", cmd->env_name[i]);
989 990 991 992 993
        if (cmd->env_value[i])
            virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
        virBufferAddLit(buf, "/>\n");
    }

994 995
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</qemu:commandline>\n");
996 997 998 999 1000 1001 1002 1003 1004 1005
    return 0;
}

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


1006 1007 1008 1009 1010 1011
virDomainXMLNamespace virQEMUDriverDomainXMLNamespace = {
    .parse = qemuDomainDefNamespaceParse,
    .free = qemuDomainDefNamespaceFree,
    .format = qemuDomainDefNamespaceFormatXML,
    .href = qemuDomainDefNamespaceHref,
};
1012

1013

1014 1015 1016
static int
qemuDomainDefPostParse(virDomainDefPtr def,
                       virCapsPtr caps,
1017
                       void *opaque)
1018
{
1019 1020
    virQEMUDriverPtr driver = opaque;
    virQEMUCapsPtr qemuCaps = NULL;
1021
    bool addDefaultUSB = true;
1022
    bool addImplicitSATA = false;
1023
    bool addPCIRoot = false;
L
Laine Stump 已提交
1024
    bool addPCIeRoot = false;
1025
    bool addDefaultMemballoon = true;
1026 1027
    bool addDefaultUSBKBD = false;
    bool addDefaultUSBMouse = false;
1028
    bool addPanicDevice = false;
1029
    int ret = -1;
1030

J
Ján Tomko 已提交
1031 1032 1033
    if (def->os.bootloader || def->os.bootloaderArgs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("bootloader is not supported by QEMU"));
1034
        return ret;
J
Ján Tomko 已提交
1035 1036
    }

1037 1038 1039
    /* check for emulator and create a default one if needed */
    if (!def->emulator &&
        !(def->emulator = virDomainDefGetDefaultEmulator(def, caps)))
1040 1041 1042 1043 1044 1045 1046
        return ret;


    /* This condition is actually a (temporary) hack for test suite which
     * does not create capabilities cache */
    if (driver && driver->qemuCapsCache)
        qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator);
1047

1048 1049 1050 1051 1052 1053
    /* 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 已提交
1054
        if (STREQ(def->os.machine, "isapc")) {
1055
            addDefaultUSB = false;
1056
            break;
1057
        }
L
Laine Stump 已提交
1058 1059
        if (STRPREFIX(def->os.machine, "pc-q35") ||
            STREQ(def->os.machine, "q35")) {
1060 1061 1062 1063
            addPCIeRoot = true;
            addDefaultUSB = false;
            addImplicitSATA = true;
            break;
L
Laine Stump 已提交
1064
        }
1065 1066
        if (!STRPREFIX(def->os.machine, "pc-0.") &&
            !STRPREFIX(def->os.machine, "pc-1.") &&
1067
            !STRPREFIX(def->os.machine, "pc-i440") &&
1068 1069 1070 1071 1072 1073
            !STREQ(def->os.machine, "pc") &&
            !STRPREFIX(def->os.machine, "rhel"))
            break;
        addPCIRoot = true;
        break;

1074
    case VIR_ARCH_ARMV7L:
1075
    case VIR_ARCH_AARCH64:
1076 1077 1078 1079 1080 1081 1082
        addDefaultUSB = false;
        addDefaultMemballoon = false;
        if (STREQ(def->os.machine, "virt") ||
            STRPREFIX(def->os.machine, "virt-")) {
            addPCIeRoot = virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_GPEX);
        }
        break;
1083

1084
    case VIR_ARCH_PPC64:
1085
    case VIR_ARCH_PPC64LE:
1086 1087 1088
        addPCIRoot = true;
        addDefaultUSBKBD = true;
        addDefaultUSBMouse = true;
1089 1090 1091 1092 1093
        /* For pSeries guests, the firmware provides the same
         * functionality as the pvpanic device, so automatically
         * add the definition if not already present */
        if (STRPREFIX(def->os.machine, "pseries"))
            addPanicDevice = true;
1094 1095
        break;

1096 1097 1098 1099 1100 1101 1102
    case VIR_ARCH_ALPHA:
    case VIR_ARCH_PPC:
    case VIR_ARCH_PPCEMB:
    case VIR_ARCH_SH4:
    case VIR_ARCH_SH4EB:
        addPCIRoot = true;
        break;
1103 1104 1105 1106 1107 1108
    case VIR_ARCH_S390:
        addDefaultUSB = false;
        break;
    case VIR_ARCH_S390X:
        addDefaultUSB = false;
        break;
1109 1110 1111 1112 1113 1114

    case VIR_ARCH_SPARC:
    case VIR_ARCH_SPARC64:
        addPCIRoot = true;
        break;

1115 1116 1117 1118
    default:
        break;
    }

1119 1120 1121
    if (addDefaultUSB &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_USB, 0, -1) < 0)
1122
        goto cleanup;
1123

1124 1125 1126
    if (addImplicitSATA &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_SATA, 0, -1) < 0)
1127
        goto cleanup;
1128

1129 1130 1131
    /* NB: any machine that sets addPCIRoot to true must also return
     * true from the function qemuDomainSupportsPCI().
     */
1132 1133 1134 1135
    if (addPCIRoot &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
            VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) < 0)
1136
        goto cleanup;
1137

1138 1139 1140
    /* 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
1141 1142 1143
     *
     * NB: any machine that sets addPCIeRoot to true must also return
     * true from the function qemuDomainSupportsPCI().
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
     */
    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) {
1155
            goto cleanup;
1156 1157
        }
    }
1158

1159
    if (addDefaultMemballoon && !def->memballoon) {
1160 1161
        virDomainMemballoonDefPtr memballoon;
        if (VIR_ALLOC(memballoon) < 0)
1162
            goto cleanup;
1163 1164 1165 1166 1167

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

1168 1169 1170 1171 1172
    if (addDefaultUSBKBD &&
        def->ngraphics > 0 &&
        virDomainDefMaybeAddInput(def,
                                  VIR_DOMAIN_INPUT_TYPE_KBD,
                                  VIR_DOMAIN_INPUT_BUS_USB) < 0)
1173
        goto cleanup;
1174 1175 1176 1177 1178 1179

    if (addDefaultUSBMouse &&
        def->ngraphics > 0 &&
        virDomainDefMaybeAddInput(def,
                                  VIR_DOMAIN_INPUT_TYPE_MOUSE,
                                  VIR_DOMAIN_INPUT_BUS_USB) < 0)
1180
        goto cleanup;
1181

1182 1183 1184
    if (addPanicDevice && !def->panic) {
        virDomainPanicDefPtr panic;
        if (VIR_ALLOC(panic) < 0)
1185
            goto cleanup;
1186 1187 1188 1189

        def->panic = panic;
    }

1190 1191 1192 1193
    ret = 0;
 cleanup:
    virObjectUnref(qemuCaps);
    return ret;
1194 1195
}

1196
static const char *
1197 1198
qemuDomainDefaultNetModel(const virDomainDef *def,
                          virQEMUCapsPtr qemuCaps)
1199
{
1200
    if (ARCH_IS_S390(def->os.arch))
1201 1202
        return "virtio";

1203 1204
    if (def->os.arch == VIR_ARCH_ARMV7L ||
        def->os.arch == VIR_ARCH_AARCH64) {
1205 1206 1207
        if (STREQ(def->os.machine, "versatilepb"))
            return "smc91c111";

1208 1209 1210
        if (STREQ(def->os.machine, "virt"))
            return "virtio";

1211 1212 1213 1214 1215
        /* Incomplete. vexpress (and a few others) use this, but not all
         * arm boards */
        return "lan9118";
    }

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    /* Try several network devices in turn; each of these devices is
     * less likely be supported out-of-the-box by the guest operating
     * system than the previous one */
    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_RTL8139))
        return "rtl8139";
    else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_E1000))
        return "e1000";
    else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_NET))
        return "virtio";

    /* We've had no luck detecting support for any network device,
     * but we have to return something: might as well be rtl8139 */
1228 1229
    return "rtl8139";
}
1230

1231 1232
static int
qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
1233
                             const virDomainDef *def,
1234
                             virCapsPtr caps ATTRIBUTE_UNUSED,
1235
                             void *opaque)
1236
{
1237
    virQEMUDriverPtr driver = opaque;
1238
    virQEMUCapsPtr qemuCaps = NULL;
1239
    virQEMUDriverConfigPtr cfg = NULL;
1240
    int ret = -1;
1241

1242 1243 1244
    if (driver)
        cfg = virQEMUDriverGetConfig(driver);

1245 1246 1247 1248 1249
    /* This condition is actually a (temporary) hack for test suite which
     * does not create capabilities cache */
    if (driver && driver->qemuCapsCache)
        qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator);

1250
    if (dev->type == VIR_DOMAIN_DEVICE_NET &&
1251 1252
        dev->data.net->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
        !dev->data.net->model) {
1253
        if (VIR_STRDUP(dev->data.net->model,
1254
                       qemuDomainDefaultNetModel(def, qemuCaps)) < 0)
1255
            goto cleanup;
1256
    }
1257

1258 1259 1260 1261 1262
    /* 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 */
1263
        if (cfg) {
1264 1265 1266
            /* assign default storage format and driver according to config */
            if (cfg->allowDiskFormatProbing) {
                /* default disk format for drives */
1267
                if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
E
Eric Blake 已提交
1268 1269
                    (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                     virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
1270
                    virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_AUTO);
1271

1272
                /* default disk format for mirrored drive */
1273
                if (disk->mirror &&
1274 1275
                    disk->mirror->format == VIR_STORAGE_FILE_NONE)
                    disk->mirror->format = VIR_STORAGE_FILE_AUTO;
1276 1277
            } else {
                /* default driver if probing is forbidden */
1278 1279
                if (!virDomainDiskGetDriver(disk) &&
                    virDomainDiskSetDriver(disk, "qemu") < 0)
1280
                    goto cleanup;
1281 1282

                /* default disk format for drives */
1283
                if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
E
Eric Blake 已提交
1284 1285
                    (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                     virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
1286
                    virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);
1287

1288
                /* default disk format for mirrored drive */
1289
                if (disk->mirror &&
1290 1291
                    disk->mirror->format == VIR_STORAGE_FILE_NONE)
                    disk->mirror->format = VIR_STORAGE_FILE_RAW;
1292
            }
1293 1294 1295
        }
    }

1296 1297 1298 1299
    /* 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 &&
1300
        ARCH_IS_S390(def->os.arch))
1301 1302
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO;

1303 1304 1305 1306 1307
    /* 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 &&
1308
        ARCH_IS_S390(def->os.arch))
1309 1310
        dev->data.controller->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE;

1311 1312 1313 1314 1315 1316 1317
    /* 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;

1318 1319 1320 1321 1322
    /* 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 &&
1323 1324 1325 1326
        !dev->data.chr->source.data.nix.path) {
        if (!cfg) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("cannot generate UNIX socket path"));
1327
            goto cleanup;
1328 1329
        }

1330 1331 1332 1333 1334 1335
        if (virAsprintf(&dev->data.chr->source.data.nix.path,
                        "%s/domain-%s/%s",
                        cfg->channelTargetDir, def->name,
                        dev->data.chr->target.name ? dev->data.chr->target.name
                        : "unknown.sock") < 0)
            goto cleanup;
1336

1337 1338 1339
        dev->data.chr->source.data.nix.listen = true;
    }

1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    /* 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;
    }

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    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 {
1365
            dev->data.video->vgamem = QEMU_QXL_VGAMEM_DEFAULT;
1366 1367 1368
        }
    }

1369 1370 1371 1372 1373
    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 "));
1374
        goto cleanup;
1375
    }
1376

1377 1378
    ret = 0;

1379
 cleanup:
1380
    virObjectUnref(qemuCaps);
1381 1382
    virObjectUnref(cfg);
    return ret;
1383 1384 1385 1386 1387
}


virDomainDefParserConfig virQEMUDriverDomainDefParserConfig = {
    .devicesPostParseCallback = qemuDomainDeviceDefPostParse,
1388
    .domainPostParseCallback = qemuDomainDefPostParse,
1389 1390 1391
};


1392
static void
1393
qemuDomainObjSaveJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1394
{
1395 1396 1397
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

    if (virDomainObjIsActive(obj)) {
1398
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, obj) < 0)
1399
            VIR_WARN("Failed to save status on vm %s", obj->def->name);
1400
    }
1401

1402
    virObjectUnref(cfg);
1403 1404
}

J
Jiri Denemark 已提交
1405
void
1406
qemuDomainObjSetJobPhase(virQEMUDriverPtr driver,
J
Jiri Denemark 已提交
1407 1408 1409 1410
                         virDomainObjPtr obj,
                         int phase)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1411
    unsigned long long me = virThreadSelfID();
J
Jiri Denemark 已提交
1412 1413 1414 1415

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

1416 1417 1418 1419 1420
    VIR_DEBUG("Setting '%s' phase to '%s'",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              qemuDomainAsyncJobPhaseToString(priv->job.asyncJob, phase));

    if (priv->job.asyncOwner && me != priv->job.asyncOwner) {
1421
        VIR_WARN("'%s' async job is owned by thread %llu",
1422 1423 1424 1425
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }

J
Jiri Denemark 已提交
1426
    priv->job.phase = phase;
1427
    priv->job.asyncOwner = me;
J
Jiri Denemark 已提交
1428 1429 1430
    qemuDomainObjSaveJob(driver, obj);
}

1431
void
1432 1433
qemuDomainObjSetAsyncJobMask(virDomainObjPtr obj,
                             unsigned long long allowedJobs)
1434 1435 1436
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1437 1438 1439 1440 1441 1442 1443
    if (!priv->job.asyncJob)
        return;

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

void
1444
qemuDomainObjDiscardAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1445 1446 1447 1448 1449 1450
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    if (priv->job.active == QEMU_JOB_ASYNC_NESTED)
        qemuDomainObjResetJob(priv);
    qemuDomainObjResetAsyncJob(priv);
1451
    qemuDomainObjSaveJob(driver, obj);
1452 1453
}

1454 1455 1456 1457 1458 1459 1460 1461 1462
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()) {
1463
        VIR_WARN("'%s' async job is owned by thread %llu",
1464 1465 1466 1467 1468 1469
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }
    priv->job.asyncOwner = 0;
}

1470
static bool
1471
qemuDomainNestedJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
1472 1473
{
    return !priv->job.asyncJob || (priv->job.mask & JOB_MASK(job)) != 0;
1474 1475
}

1476
bool
1477
qemuDomainJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
1478 1479 1480 1481
{
    return !priv->job.active && qemuDomainNestedJobAllowed(priv, job);
}

1482 1483 1484
/* Give up waiting for mutex after 30 seconds */
#define QEMU_JOB_WAIT_TIME (1000ull * 30)

1485
/*
1486
 * obj must be locked before calling
1487
 */
1488
static int ATTRIBUTE_NONNULL(1)
1489
qemuDomainObjBeginJobInternal(virQEMUDriverPtr driver,
1490
                              virDomainObjPtr obj,
1491 1492
                              qemuDomainJob job,
                              qemuDomainAsyncJob asyncJob)
1493 1494
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
J
Jiri Denemark 已提交
1495
    unsigned long long now;
1496
    unsigned long long then;
1497
    bool nested = job == QEMU_JOB_ASYNC_NESTED;
1498
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1499
    const char *blocker = NULL;
J
Jiri Denemark 已提交
1500
    int ret = -1;
J
Jiri Denemark 已提交
1501 1502
    unsigned long long duration = 0;
    unsigned long long asyncDuration = 0;
1503

1504 1505 1506 1507 1508 1509
    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);

1510 1511
    if (virTimeMillisNow(&now) < 0) {
        virObjectUnref(cfg);
1512
        return -1;
1513 1514
    }

1515
    priv->jobs_queued++;
J
Jiri Denemark 已提交
1516
    then = now + QEMU_JOB_WAIT_TIME;
1517

1518
 retry:
1519 1520
    if (cfg->maxQueuedJobs &&
        priv->jobs_queued > cfg->maxQueuedJobs) {
1521 1522 1523
        goto error;
    }

1524
    while (!nested && !qemuDomainNestedJobAllowed(priv, job)) {
1525
        VIR_DEBUG("Waiting for async job (vm=%p name=%s)", obj, obj->def->name);
1526
        if (virCondWaitUntil(&priv->job.asyncCond, &obj->parent.lock, then) < 0)
1527 1528 1529
            goto error;
    }

1530
    while (priv->job.active) {
1531
        VIR_DEBUG("Waiting for job (vm=%p name=%s)", obj, obj->def->name);
1532
        if (virCondWaitUntil(&priv->job.cond, &obj->parent.lock, then) < 0)
1533
            goto error;
1534
    }
1535 1536 1537

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

1541
    qemuDomainObjResetJob(priv);
1542

J
Jiri Denemark 已提交
1543 1544
    ignore_value(virTimeMillisNow(&now));

1545
    if (job != QEMU_JOB_ASYNC) {
1546
        VIR_DEBUG("Started job: %s (async=%s vm=%p name=%s)",
1547
                   qemuDomainJobTypeToString(job),
1548 1549
                  qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                  obj, obj->def->name);
1550
        priv->job.active = job;
1551
        priv->job.owner = virThreadSelfID();
1552
        priv->job.ownerAPI = virThreadJobGet();
J
Jiri Denemark 已提交
1553
        priv->job.started = now;
1554
    } else {
1555 1556 1557
        VIR_DEBUG("Started async job: %s (vm=%p name=%s)",
                  qemuDomainAsyncJobTypeToString(asyncJob),
                  obj, obj->def->name);
1558
        qemuDomainObjResetAsyncJob(priv);
J
Jiri Denemark 已提交
1559 1560
        if (VIR_ALLOC(priv->job.current) < 0)
            goto cleanup;
1561
        priv->job.asyncJob = asyncJob;
1562
        priv->job.asyncOwner = virThreadSelfID();
1563
        priv->job.asyncOwnerAPI = virThreadJobGet();
J
Jiri Denemark 已提交
1564
        priv->job.asyncStarted = now;
J
Jiri Denemark 已提交
1565
        priv->job.current->started = now;
1566
    }
1567

1568 1569
    if (qemuDomainTrackJob(job))
        qemuDomainObjSaveJob(driver, obj);
1570

1571
    virObjectUnref(cfg);
1572
    return 0;
1573

1574
 error:
J
Jiri Denemark 已提交
1575 1576 1577 1578 1579 1580
    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;

1581
    VIR_WARN("Cannot start job (%s, %s) for domain %s; "
J
Jiri Denemark 已提交
1582 1583
             "current job is (%s, %s) owned by (%llu %s, %llu %s) "
             "for (%llus, %llus)",
1584 1585 1586 1587 1588
             qemuDomainJobTypeToString(job),
             qemuDomainAsyncJobTypeToString(asyncJob),
             obj->def->name,
             qemuDomainJobTypeToString(priv->job.active),
             qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
1589
             priv->job.owner, NULLSTR(priv->job.ownerAPI),
J
Jiri Denemark 已提交
1590 1591
             priv->job.asyncOwner, NULLSTR(priv->job.asyncOwnerAPI),
             duration / 1000, asyncDuration / 1000);
1592 1593 1594 1595 1596

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

1598 1599
    ret = -1;
    if (errno == ETIMEDOUT) {
1600 1601 1602 1603 1604 1605 1606 1607
        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"));
        }
1608 1609 1610
        ret = -2;
    } else if (cfg->maxQueuedJobs &&
               priv->jobs_queued > cfg->maxQueuedJobs) {
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
        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"));
        }
1621 1622
        ret = -2;
    } else {
1623
        virReportSystemError(errno, "%s", _("cannot acquire job mutex"));
1624
    }
J
Jiri Denemark 已提交
1625 1626

 cleanup:
1627
    priv->jobs_queued--;
1628
    virObjectUnref(cfg);
1629
    return ret;
1630 1631 1632
}

/*
1633
 * obj must be locked before calling
1634 1635 1636 1637
 *
 * This must be called by anything that will change the VM state
 * in any way, or anything that will use the QEMU monitor.
 *
1638
 * Successful calls must be followed by EndJob eventually
1639
 */
1640
int qemuDomainObjBeginJob(virQEMUDriverPtr driver,
1641
                          virDomainObjPtr obj,
1642
                          qemuDomainJob job)
1643
{
1644 1645 1646 1647 1648
    if (qemuDomainObjBeginJobInternal(driver, obj, job,
                                      QEMU_ASYNC_JOB_NONE) < 0)
        return -1;
    else
        return 0;
1649 1650
}

1651
int qemuDomainObjBeginAsyncJob(virQEMUDriverPtr driver,
1652
                               virDomainObjPtr obj,
1653
                               qemuDomainAsyncJob asyncJob)
1654
{
1655 1656 1657 1658 1659
    if (qemuDomainObjBeginJobInternal(driver, obj, QEMU_JOB_ASYNC,
                                      asyncJob) < 0)
        return -1;
    else
        return 0;
1660 1661
}

1662
static int ATTRIBUTE_RETURN_CHECK
1663 1664
qemuDomainObjBeginNestedJob(virQEMUDriverPtr driver,
                            virDomainObjPtr obj,
1665
                            qemuDomainAsyncJob asyncJob)
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
{
    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()) {
1676
        VIR_WARN("This thread doesn't seem to be the async job owner: %llu",
1677 1678 1679 1680 1681 1682 1683 1684
                 priv->job.asyncOwner);
    }

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

1685

1686
/*
1687
 * obj must be locked and have a reference before calling
1688 1689 1690 1691
 *
 * To be called after completing the work associated with the
 * earlier qemuDomainBeginJob() call
 */
1692 1693
void
qemuDomainObjEndJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1694 1695
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1696
    qemuDomainJob job = priv->job.active;
1697

1698 1699
    priv->jobs_queued--;

1700
    VIR_DEBUG("Stopping job: %s (async=%s vm=%p name=%s)",
1701
              qemuDomainJobTypeToString(job),
1702 1703
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
1704

1705
    qemuDomainObjResetJob(priv);
1706 1707
    if (qemuDomainTrackJob(job))
        qemuDomainObjSaveJob(driver, obj);
1708
    virCondSignal(&priv->job.cond);
1709 1710
}

1711
void
1712
qemuDomainObjEndAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
1713 1714
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1715

1716 1717
    priv->jobs_queued--;

1718 1719 1720
    VIR_DEBUG("Stopping async job: %s (vm=%p name=%s)",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
1721

1722
    qemuDomainObjResetAsyncJob(priv);
1723
    qemuDomainObjSaveJob(driver, obj);
1724 1725 1726
    virCondBroadcast(&priv->job.asyncCond);
}

1727 1728 1729 1730 1731
void
qemuDomainObjAbortAsyncJob(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1732 1733 1734
    VIR_DEBUG("Requesting abort of async job: %s (vm=%p name=%s)",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
1735

1736 1737
    priv->job.abortJob = true;
    virDomainObjBroadcast(obj);
1738 1739
}

1740 1741 1742 1743 1744 1745 1746 1747 1748
/*
 * 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
 */
1749
static int
1750
qemuDomainObjEnterMonitorInternal(virQEMUDriverPtr driver,
1751
                                  virDomainObjPtr obj,
1752
                                  qemuDomainAsyncJob asyncJob)
1753 1754 1755
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1756
    if (asyncJob != QEMU_ASYNC_JOB_NONE) {
1757 1758 1759
        int ret;
        if ((ret = qemuDomainObjBeginNestedJob(driver, obj, asyncJob)) < 0)
            return ret;
1760
        if (!virDomainObjIsActive(obj)) {
1761 1762
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
1763
            qemuDomainObjEndJob(driver, obj);
1764 1765
            return -1;
        }
1766 1767 1768
    } 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");
1769 1770
    }

1771 1772
    VIR_DEBUG("Entering monitor (mon=%p vm=%p name=%s)",
              priv->mon, obj, obj->def->name);
1773
    virObjectLock(priv->mon);
1774
    virObjectRef(priv->mon);
1775
    ignore_value(virTimeMillisNow(&priv->monStart));
1776
    virObjectUnlock(obj);
1777 1778

    return 0;
1779 1780
}

1781
static void ATTRIBUTE_NONNULL(1)
1782
qemuDomainObjExitMonitorInternal(virQEMUDriverPtr driver,
1783
                                 virDomainObjPtr obj)
1784 1785
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
1786
    bool hasRefs;
1787

1788
    hasRefs = virObjectUnref(priv->mon);
1789

1790
    if (hasRefs)
1791
        virObjectUnlock(priv->mon);
1792

1793
    virObjectLock(obj);
1794 1795
    VIR_DEBUG("Exited monitor (mon=%p vm=%p name=%s)",
              priv->mon, obj, obj->def->name);
1796

1797
    priv->monStart = 0;
1798
    if (!hasRefs)
1799
        priv->mon = NULL;
1800

1801 1802 1803 1804 1805
    if (priv->job.active == QEMU_JOB_ASYNC_NESTED) {
        qemuDomainObjResetJob(priv);
        qemuDomainObjSaveJob(driver, obj);
        virCondSignal(&priv->job.cond);
    }
1806 1807
}

1808
void qemuDomainObjEnterMonitor(virQEMUDriverPtr driver,
1809
                               virDomainObjPtr obj)
1810
{
1811
    ignore_value(qemuDomainObjEnterMonitorInternal(driver, obj,
1812
                                                   QEMU_ASYNC_JOB_NONE));
1813 1814
}

1815
/* obj must NOT be locked before calling
1816 1817
 *
 * Should be paired with an earlier qemuDomainObjEnterMonitor() call
1818 1819 1820 1821 1822 1823
 *
 * 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.
1824
 */
1825 1826
int qemuDomainObjExitMonitor(virQEMUDriverPtr driver,
                             virDomainObjPtr obj)
1827
{
1828
    qemuDomainObjExitMonitorInternal(driver, obj);
1829
    if (!virDomainObjIsActive(obj)) {
1830 1831 1832
        if (!virGetLastError())
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
1833 1834 1835
        return -1;
    }
    return 0;
1836
}
1837 1838

/*
1839
 * obj must be locked before calling
1840 1841
 *
 * To be called immediately before any QEMU monitor API call.
1842
 * Must have already either called qemuDomainObjBeginJob()
1843 1844 1845 1846 1847
 * 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
1848 1849 1850
 * 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).
1851 1852
 */
int
1853
qemuDomainObjEnterMonitorAsync(virQEMUDriverPtr driver,
1854
                               virDomainObjPtr obj,
1855
                               qemuDomainAsyncJob asyncJob)
1856
{
1857
    return qemuDomainObjEnterMonitorInternal(driver, obj, asyncJob);
1858 1859
}

D
Daniel P. Berrange 已提交
1860 1861


1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
/*
 * 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 已提交
1873 1874 1875
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

1876 1877
    VIR_DEBUG("Entering agent (agent=%p vm=%p name=%s)",
              priv->agent, obj, obj->def->name);
1878
    virObjectLock(priv->agent);
1879
    virObjectRef(priv->agent);
D
Daniel P. Berrange 已提交
1880
    ignore_value(virTimeMillisNow(&priv->agentStart));
1881
    virObjectUnlock(obj);
D
Daniel P. Berrange 已提交
1882 1883
}

1884 1885 1886 1887 1888 1889 1890

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

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

1897
    if (hasRefs)
1898
        virObjectUnlock(priv->agent);
D
Daniel P. Berrange 已提交
1899

1900
    virObjectLock(obj);
1901 1902
    VIR_DEBUG("Exited agent (agent=%p vm=%p name=%s)",
              priv->agent, obj, obj->def->name);
D
Daniel P. Berrange 已提交
1903 1904

    priv->agentStart = 0;
1905
    if (!hasRefs)
D
Daniel P. Berrange 已提交
1906 1907 1908
        priv->agent = NULL;
}

1909
void qemuDomainObjEnterRemote(virDomainObjPtr obj)
1910
{
1911 1912
    VIR_DEBUG("Entering remote (vm=%p name=%s)",
              obj, obj->def->name);
1913
    virObjectUnlock(obj);
1914 1915
}

1916
void qemuDomainObjExitRemote(virDomainObjPtr obj)
1917
{
1918
    virObjectLock(obj);
1919 1920
    VIR_DEBUG("Exited remote (vm=%p name=%s)",
              obj, obj->def->name);
1921
}
1922 1923


1924 1925 1926 1927 1928 1929 1930 1931
virDomainDefPtr
qemuDomainDefCopy(virQEMUDriverPtr driver,
                  virDomainDefPtr src,
                  unsigned int flags)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    virDomainDefPtr ret = NULL;
    virCapsPtr caps = NULL;
1932
    char *xml = NULL;
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

    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,
1943
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
1944 1945
        goto cleanup;

1946
 cleanup:
1947 1948 1949 1950 1951
    VIR_FREE(xml);
    virObjectUnref(caps);
    return ret;
}

1952
int
1953
qemuDomainDefFormatBuf(virQEMUDriverPtr driver,
1954 1955 1956
                       virDomainDefPtr def,
                       unsigned int flags,
                       virBuffer *buf)
1957
{
1958
    int ret = -1;
1959
    virCPUDefPtr cpu = NULL;
1960
    virCPUDefPtr def_cpu = def->cpu;
1961 1962
    virDomainControllerDefPtr *controllers = NULL;
    int ncontrollers = 0;
1963 1964 1965 1966
    virCapsPtr caps = NULL;

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

    /* Update guest CPU requirements according to host CPU */
1969 1970 1971
    if ((flags & VIR_DOMAIN_XML_UPDATE_CPU) &&
        def_cpu &&
        (def_cpu->mode != VIR_CPU_MODE_CUSTOM || def_cpu->model)) {
1972 1973
        if (!caps->host.cpu ||
            !caps->host.cpu->model) {
1974 1975
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("cannot get host CPU capabilities"));
1976 1977 1978
            goto cleanup;
        }

1979
        if (!(cpu = virCPUDefCopy(def_cpu)) ||
1980
            cpuUpdate(cpu, caps->host.cpu) < 0)
1981 1982 1983 1984
            goto cleanup;
        def->cpu = cpu;
    }

1985
    if ((flags & VIR_DOMAIN_XML_MIGRATABLE)) {
1986
        size_t i;
1987
        int toremove = 0;
1988
        virDomainControllerDefPtr usb = NULL, pci = NULL;
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006

        /* 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);
2007
            toremove++;
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
        } 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 已提交
2026
            VIR_DEBUG("Removing default pci-root from domain '%s'"
2027
                      " for migration compatibility", def->name);
2028
            toremove++;
2029 2030 2031 2032
        } else {
            pci = NULL;
        }

2033
        if (toremove) {
2034 2035
            controllers = def->controllers;
            ncontrollers = def->ncontrollers;
2036
            if (VIR_ALLOC_N(def->controllers, ncontrollers - toremove) < 0) {
2037 2038 2039 2040 2041 2042
                controllers = NULL;
                goto cleanup;
            }

            def->ncontrollers = 0;
            for (i = 0; i < ncontrollers; i++) {
2043
                if (controllers[i] != usb && controllers[i] != pci)
2044 2045 2046
                    def->controllers[def->ncontrollers++] = controllers[i];
            }
        }
2047 2048


2049 2050
    }

2051 2052 2053
    ret = virDomainDefFormatInternal(def,
                                     virDomainDefFormatConvertXMLFlags(flags),
                                     buf);
2054

2055
 cleanup:
2056 2057
    def->cpu = def_cpu;
    virCPUDefFree(cpu);
2058 2059 2060 2061 2062
    if (controllers) {
        VIR_FREE(def->controllers);
        def->controllers = controllers;
        def->ncontrollers = ncontrollers;
    }
2063
    virObjectUnref(caps);
2064 2065
    return ret;
}
2066

2067
char *qemuDomainDefFormatXML(virQEMUDriverPtr driver,
2068
                             virDomainDefPtr def,
2069
                             unsigned int flags)
2070 2071 2072
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

2073
    if (qemuDomainDefFormatBuf(driver, def, flags, &buf) < 0) {
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
        virBufferFreeAndReset(&buf);
        return NULL;
    }

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

    return virBufferContentAndReset(&buf);
}

2087
char *qemuDomainFormatXML(virQEMUDriverPtr driver,
2088
                          virDomainObjPtr vm,
2089
                          unsigned int flags)
2090 2091 2092 2093 2094 2095 2096 2097
{
    virDomainDefPtr def;

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

2098
    return qemuDomainDefFormatXML(driver, def, flags);
2099 2100
}

2101
char *
2102
qemuDomainDefFormatLive(virQEMUDriverPtr driver,
2103
                        virDomainDefPtr def,
2104 2105
                        bool inactive,
                        bool compatible)
2106 2107 2108 2109 2110
{
    unsigned int flags = QEMU_DOMAIN_FORMAT_LIVE_FLAGS;

    if (inactive)
        flags |= VIR_DOMAIN_XML_INACTIVE;
2111 2112
    if (compatible)
        flags |= VIR_DOMAIN_XML_MIGRATABLE;
2113

2114
    return qemuDomainDefFormatXML(driver, def, flags);
2115 2116
}

2117

2118
void qemuDomainObjTaint(virQEMUDriverPtr driver,
2119
                        virDomainObjPtr obj,
2120
                        virDomainTaintFlags taint,
2121
                        int logFD)
2122
{
2123 2124
    virErrorPtr orig_err = NULL;

2125 2126 2127 2128 2129 2130 2131 2132 2133
    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));
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147

        /* 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);
        }
2148 2149 2150 2151
    }
}


2152
void qemuDomainObjCheckTaint(virQEMUDriverPtr driver,
2153 2154
                             virDomainObjPtr obj,
                             int logFD)
2155
{
2156
    size_t i;
2157
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2158
    qemuDomainObjPrivatePtr priv = obj->privateData;
2159

2160
    if (virQEMUDriverIsPrivileged(driver) &&
2161 2162 2163
        (!cfg->clearEmulatorCapabilities ||
         cfg->user == 0 ||
         cfg->group == 0))
2164
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES, logFD);
2165

2166 2167 2168
    if (priv->hookRun)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOOK, logFD);

2169 2170 2171
    if (obj->def->namespaceData) {
        qemuDomainCmdlineDefPtr qemucmd = obj->def->namespaceData;
        if (qemucmd->num_args || qemucmd->num_env)
2172
            qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_ARGV, logFD);
2173 2174
    }

2175 2176 2177
    if (obj->def->cpu && obj->def->cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOST_CPU, logFD);

2178
    for (i = 0; i < obj->def->ndisks; i++)
2179
        qemuDomainObjCheckDiskTaint(driver, obj, obj->def->disks[i], logFD);
2180

2181 2182 2183 2184
    for (i = 0; i < obj->def->nhostdevs; i++)
        qemuDomainObjCheckHostdevTaint(driver, obj, obj->def->hostdevs[i],
                                       logFD);

2185
    for (i = 0; i < obj->def->nnets; i++)
2186
        qemuDomainObjCheckNetTaint(driver, obj, obj->def->nets[i], logFD);
2187

2188 2189 2190
    if (obj->def->os.dtb)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_DTB, logFD);

2191
    virObjectUnref(cfg);
2192 2193 2194
}


2195
void qemuDomainObjCheckDiskTaint(virQEMUDriverPtr driver,
2196
                                 virDomainObjPtr obj,
2197 2198
                                 virDomainDiskDefPtr disk,
                                 int logFD)
2199
{
2200
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2201
    int format = virDomainDiskGetFormat(disk);
2202

2203
    if ((!format || format == VIR_STORAGE_FILE_AUTO) &&
2204
        cfg->allowDiskFormatProbing)
2205
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_DISK_PROBING, logFD);
2206

2207 2208 2209
    if (disk->rawio == VIR_TRISTATE_BOOL_YES)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES,
                           logFD);
2210

2211 2212 2213 2214 2215 2216
    if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
        virStorageSourceGetActualType(disk->src) == VIR_STORAGE_TYPE_BLOCK &&
        disk->src->path)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CDROM_PASSTHROUGH,
                           logFD);

2217
    virObjectUnref(cfg);
2218 2219 2220
}


2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
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);
}


2235
void qemuDomainObjCheckNetTaint(virQEMUDriverPtr driver,
2236
                                virDomainObjPtr obj,
2237 2238
                                virDomainNetDefPtr net,
                                int logFD)
2239
{
2240 2241 2242 2243 2244 2245
    /* 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)
2246
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_SHELL_SCRIPTS, logFD);
2247
}
2248 2249 2250


static int
2251
qemuDomainOpenLogHelper(virQEMUDriverConfigPtr cfg,
2252
                        virDomainObjPtr vm,
E
Eric Blake 已提交
2253
                        int oflags,
2254 2255 2256 2257
                        mode_t mode)
{
    char *logfile;
    int fd = -1;
2258
    bool trunc = false;
2259

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

2263 2264 2265 2266 2267 2268 2269 2270 2271
    /* 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 已提交
2272
    if ((fd = open(logfile, oflags, mode)) < 0) {
2273 2274 2275 2276 2277 2278 2279
        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);
2280 2281 2282 2283 2284 2285 2286
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }
    if (trunc &&
        ftruncate(fd, 0) < 0) {
        virReportSystemError(errno, _("failed to truncate %s"),
                             logfile);
2287 2288 2289 2290
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }

2291
 cleanup:
2292 2293 2294 2295 2296 2297
    VIR_FREE(logfile);
    return fd;
}


int
2298
qemuDomainCreateLog(virQEMUDriverPtr driver, virDomainObjPtr vm,
E
Eric Blake 已提交
2299
                    bool append)
2300
{
2301
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
E
Eric Blake 已提交
2302
    int oflags;
2303
    int ret;
2304

E
Eric Blake 已提交
2305
    oflags = O_CREAT | O_WRONLY;
2306
    /* Only logrotate files in /var/log, so only append if running privileged */
2307
    if (virQEMUDriverIsPrivileged(driver) || append)
E
Eric Blake 已提交
2308
        oflags |= O_APPEND;
2309
    else
E
Eric Blake 已提交
2310
        oflags |= O_TRUNC;
2311

2312 2313 2314
    ret = qemuDomainOpenLogHelper(cfg, vm, oflags, S_IRUSR | S_IWUSR);
    virObjectUnref(cfg);
    return ret;
2315 2316 2317 2318
}


int
2319
qemuDomainOpenLog(virQEMUDriverPtr driver, virDomainObjPtr vm, off_t pos)
2320
{
2321
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2322 2323 2324 2325
    int fd;
    off_t off;
    int whence;

2326 2327 2328
    fd = qemuDomainOpenLogHelper(cfg, vm, O_RDONLY, 0);
    virObjectUnref(cfg);
    if (fd < 0)
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
        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;
}


2355
int qemuDomainAppendLog(virQEMUDriverPtr driver,
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
                        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;

2371
    if (virVasprintf(&message, fmt, argptr) < 0)
2372 2373 2374 2375 2376 2377 2378 2379 2380
        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;

2381
 cleanup:
2382 2383 2384 2385 2386
    va_end(argptr);

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

O
Osier Yang 已提交
2387
    VIR_FREE(message);
2388 2389
    return ret;
}
2390 2391 2392

/* Locate an appropriate 'qemu-img' binary.  */
const char *
2393
qemuFindQemuImgBinary(virQEMUDriverPtr driver)
2394
{
2395 2396 2397
    if (!driver->qemuImgBinary)
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unable to find kvm-img or qemu-img"));
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413

    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);
2414 2415 2416 2417
    newxml = virDomainSnapshotDefFormat(
        uuidstr, snapshot->def,
        virDomainDefFormatConvertXMLFlags(QEMU_DOMAIN_FORMAT_LIVE_FLAGS),
        1);
2418
    if (newxml == NULL)
2419 2420
        return -1;

2421
    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0)
2422 2423 2424 2425 2426 2427 2428
        goto cleanup;
    if (virFileMakePath(snapDir) < 0) {
        virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
                             snapDir);
        goto cleanup;
    }

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

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

2434
 cleanup:
2435 2436 2437 2438 2439 2440 2441 2442
    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.  */
2443
static int
2444
qemuDomainSnapshotForEachQcow2Raw(virQEMUDriverPtr driver,
2445 2446 2447 2448 2449
                                  virDomainDefPtr def,
                                  const char *name,
                                  const char *op,
                                  bool try_all,
                                  int ndisks)
2450 2451
{
    const char *qemuimgarg[] = { NULL, "snapshot", NULL, NULL, NULL, NULL };
2452
    size_t i;
2453 2454 2455 2456 2457 2458 2459 2460 2461
    bool skipped = false;

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

    qemuimgarg[2] = op;
2462
    qemuimgarg[3] = name;
2463

2464
    for (i = 0; i < ndisks; i++) {
2465
        /* FIXME: we also need to handle LVM here */
2466
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
2467 2468 2469
            int format = virDomainDiskGetFormat(def->disks[i]);

            if (format > 0 && format != VIR_STORAGE_FILE_QCOW2) {
2470 2471 2472 2473 2474
                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",
2475
                             def->disks[i]->dst);
2476 2477
                    skipped = true;
                    continue;
2478 2479 2480 2481 2482
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
2483
                }
2484 2485 2486 2487
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Disk device '%s' does not support"
                                 " snapshotting"),
                               def->disks[i]->dst);
2488 2489 2490
                return -1;
            }

2491
            qemuimgarg[4] = virDomainDiskGetSource(def->disks[i]);
2492 2493 2494 2495

            if (virRun(qemuimgarg, NULL) < 0) {
                if (try_all) {
                    VIR_WARN("skipping snapshot action on %s",
2496
                             def->disks[i]->dst);
2497 2498
                    skipped = true;
                    continue;
2499 2500 2501 2502 2503
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
2504 2505 2506 2507 2508 2509 2510 2511 2512
                }
                return -1;
            }
        }
    }

    return skipped ? 1 : 0;
}

2513 2514 2515
/* 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
2516
qemuDomainSnapshotForEachQcow2(virQEMUDriverPtr driver,
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
                               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);
}

2533 2534
/* Discard one snapshot (or its metadata), without reparenting any children.  */
int
2535
qemuDomainSnapshotDiscard(virQEMUDriverPtr driver,
2536 2537 2538 2539 2540 2541 2542 2543 2544
                          virDomainObjPtr vm,
                          virDomainSnapshotObjPtr snap,
                          bool update_current,
                          bool metadata_only)
{
    char *snapFile = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap = NULL;
2545
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2546 2547 2548 2549 2550 2551 2552 2553 2554

    if (!metadata_only) {
        if (!virDomainObjIsActive(vm)) {
            /* Ignore any skipped disks */
            if (qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-d",
                                               true) < 0)
                goto cleanup;
        } else {
            priv = vm->privateData;
2555
            qemuDomainObjEnterMonitor(driver, vm);
2556 2557
            /* we continue on even in the face of error */
            qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
2558
            ignore_value(qemuDomainObjExitMonitor(driver, vm));
2559 2560 2561
        }
    }

2562
    if (virAsprintf(&snapFile, "%s/%s/%s.xml", cfg->snapshotDir,
2563
                    vm->def->name, snap->def->name) < 0)
2564 2565 2566 2567
        goto cleanup;

    if (snap == vm->current_snapshot) {
        if (update_current && snap->def->parent) {
2568
            parentsnap = virDomainSnapshotFindByName(vm->snapshots,
2569 2570 2571 2572 2573 2574 2575
                                                     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,
2576
                                                    cfg->snapshotDir) < 0) {
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
                    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);
2589
    virDomainSnapshotObjListRemove(vm->snapshots, snap);
2590 2591 2592

    ret = 0;

2593
 cleanup:
2594
    VIR_FREE(snapFile);
2595
    virObjectUnref(cfg);
2596 2597 2598 2599 2600 2601 2602 2603 2604
    return ret;
}

/* Hash iterator callback to discard multiple snapshots.  */
void qemuDomainSnapshotDiscardAll(void *payload,
                                  const void *name ATTRIBUTE_UNUSED,
                                  void *data)
{
    virDomainSnapshotObjPtr snap = payload;
2605
    virQEMUSnapRemovePtr curr = data;
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
    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
2617
qemuDomainSnapshotDiscardAllMetadata(virQEMUDriverPtr driver,
2618 2619
                                     virDomainObjPtr vm)
{
2620
    virQEMUSnapRemove rem;
2621 2622 2623 2624 2625

    rem.driver = driver;
    rem.vm = vm;
    rem.metadata_only = true;
    rem.err = 0;
2626 2627
    virDomainSnapshotForEach(vm->snapshots, qemuDomainSnapshotDiscardAll,
                             &rem);
2628 2629 2630 2631 2632

    return rem.err;
}

/*
2633
 * The caller must hold a lock the vm.
2634 2635
 */
void
2636
qemuDomainRemoveInactive(virQEMUDriverPtr driver,
2637 2638
                         virDomainObjPtr vm)
{
2639
    bool haveJob = true;
2640
    char *snapDir;
2641
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2642

2643 2644 2645
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        haveJob = false;

2646 2647 2648 2649 2650
    /* 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);
    }
2651
    else if (virAsprintf(&snapDir, "%s/%s", cfg->snapshotDir,
2652 2653
                         vm->def->name) < 0) {
        VIR_WARN("unable to remove snapshot directory %s/%s",
2654
                 cfg->snapshotDir, vm->def->name);
2655 2656 2657 2658 2659
    } else {
        if (rmdir(snapDir) < 0 && errno != ENOENT)
            VIR_WARN("unable to remove snapshot directory %s", snapDir);
        VIR_FREE(snapDir);
    }
2660 2661 2662

    virObjectRef(vm);

2663
    virDomainObjListRemove(driver->domains, vm);
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
    /*
     * virDomainObjListRemove() leaves the domain unlocked so it can
     * be unref'd for other drivers that depend on that, but we still
     * need to reset a job and we have a reference from the API that
     * called this function.  So we need to lock it back.  This is
     * just a workaround for the qemu driver.
     *
     * XXX: Ideally, the global handling of domain objects and object
     *      lists would be refactored so we don't need hacks like
     *      this, but since that requires refactor of all drivers,
     *      it's a work for another day.
     */
    virObjectLock(vm);
2677
    virObjectUnref(cfg);
2678 2679

    if (haveJob)
2680
        qemuDomainObjEndJob(driver, vm);
2681 2682

    virObjectUnref(vm);
2683
}
2684 2685

void
2686
qemuDomainSetFakeReboot(virQEMUDriverPtr driver,
2687 2688 2689 2690
                        virDomainObjPtr vm,
                        bool value)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2691
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2692 2693

    if (priv->fakeReboot == value)
2694
        goto cleanup;
2695 2696 2697

    priv->fakeReboot = value;

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

2701
 cleanup:
2702
    virObjectUnref(cfg);
2703
}
M
Michal Privoznik 已提交
2704

2705 2706 2707
static int
qemuDomainCheckRemoveOptionalDisk(virQEMUDriverPtr driver,
                                  virDomainObjPtr vm,
2708
                                  size_t diskIndex)
2709 2710
{
    char uuid[VIR_UUID_STRING_BUFLEN];
2711
    virObjectEventPtr event = NULL;
2712
    virDomainDiskDefPtr disk = vm->def->disks[diskIndex];
2713
    const char *src = virDomainDiskGetSource(disk);
2714 2715 2716 2717 2718

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

    VIR_DEBUG("Dropping disk '%s' on domain '%s' (UUID '%s') "
              "due to inaccessible source '%s'",
2719
              disk->dst, vm->def->name, uuid, src);
2720 2721 2722 2723

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

2724
        event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
2725 2726
                                                   disk->info.alias,
                                                   VIR_DOMAIN_EVENT_DISK_CHANGE_MISSING_ON_START);
2727
        ignore_value(virDomainDiskSetSource(disk, NULL));
2728
    } else {
2729
        event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
2730 2731
                                                   disk->info.alias,
                                                   VIR_DOMAIN_EVENT_DISK_DROP_MISSING_ON_START);
2732 2733
        virDomainDiskRemove(vm->def, diskIndex);
        virDomainDiskDefFree(disk);
2734 2735
    }

2736
    qemuDomainEventQueue(driver, event);
2737 2738 2739 2740

    return 0;
}

2741 2742 2743
static int
qemuDomainCheckDiskStartupPolicy(virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
2744
                                 size_t diskIndex,
2745 2746
                                 bool cold_boot)
{
2747
    int startupPolicy = vm->def->disks[diskIndex]->startupPolicy;
2748
    int device = vm->def->disks[diskIndex]->device;
2749

2750
    switch ((virDomainStartupPolicy) startupPolicy) {
2751
        case VIR_DOMAIN_STARTUP_POLICY_OPTIONAL:
2752 2753 2754 2755 2756 2757 2758
            /* 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;
2759 2760 2761 2762 2763 2764
            break;

        case VIR_DOMAIN_STARTUP_POLICY_MANDATORY:
            goto error;

        case VIR_DOMAIN_STARTUP_POLICY_REQUISITE:
2765
            if (cold_boot)
2766 2767 2768 2769 2770 2771 2772 2773 2774
                goto error;
            break;

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

2775
    if (qemuDomainCheckRemoveOptionalDisk(driver, vm, diskIndex) < 0)
2776
        goto error;
2777 2778 2779

    return 0;

2780
 error:
2781 2782 2783
    return -1;
}

2784

M
Michal Privoznik 已提交
2785
int
2786
qemuDomainCheckDiskPresence(virQEMUDriverPtr driver,
M
Michal Privoznik 已提交
2787
                            virDomainObjPtr vm,
2788
                            bool cold_boot)
M
Michal Privoznik 已提交
2789 2790
{
    int ret = -1;
2791
    size_t i;
M
Michal Privoznik 已提交
2792

2793
    VIR_DEBUG("Checking for disk presence");
2794
    for (i = vm->def->ndisks; i > 0; i--) {
2795 2796
        size_t idx = i - 1;
        virDomainDiskDefPtr disk = vm->def->disks[idx];
2797
        virStorageFileFormat format = virDomainDiskGetFormat(disk);
M
Michal Privoznik 已提交
2798

2799
        if (virStorageSourceIsEmpty(disk->src))
2800 2801 2802 2803 2804
            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 */
2805
        if (virStorageSourceIsLocalStorage(disk->src) &&
2806
            format >= VIR_STORAGE_FILE_NONE &&
2807
            format < VIR_STORAGE_FILE_BACKING &&
2808
            virFileExists(virDomainDiskGetSource(disk)))
M
Michal Privoznik 已提交
2809 2810
            continue;

2811
        if (qemuDomainDetermineDiskChain(driver, vm, disk, true, true) >= 0)
M
Michal Privoznik 已提交
2812
            continue;
2813

2814
        if (disk->startupPolicy &&
2815
            qemuDomainCheckDiskStartupPolicy(driver, vm, idx,
2816 2817 2818
                                             cold_boot) >= 0) {
            virResetLastError();
            continue;
M
Michal Privoznik 已提交
2819 2820
        }

2821
        goto error;
M
Michal Privoznik 已提交
2822 2823 2824 2825
    }

    ret = 0;

2826
 error:
M
Michal Privoznik 已提交
2827 2828
    return ret;
}
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838

/*
 * The vm must be locked when any of the following cleanup functions is
 * called.
 */
int
qemuDomainCleanupAdd(virDomainObjPtr vm,
                     qemuDomainCleanupCallback cb)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2839
    size_t i;
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849

    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,
2850
                     priv->ncleanupCallbacks, 1) < 0)
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
        return -1;

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

void
qemuDomainCleanupRemove(virDomainObjPtr vm,
                        qemuDomainCleanupCallback cb)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2862
    size_t i;
2863 2864 2865 2866

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

    for (i = 0; i < priv->ncleanupCallbacks; i++) {
2867 2868 2869
        if (priv->cleanupCallbacks[i] == cb)
            VIR_DELETE_ELEMENT_INPLACE(priv->cleanupCallbacks,
                                       i, priv->ncleanupCallbacks);
2870 2871 2872 2873 2874 2875 2876 2877
    }

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

void
2878
qemuDomainCleanupRun(virQEMUDriverPtr driver,
2879 2880 2881
                     virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2882
    size_t i;
2883 2884 2885 2886

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

    /* run cleanup callbacks in reverse order */
2887 2888
    for (i = 0; i < priv->ncleanupCallbacks; i++) {
        if (priv->cleanupCallbacks[priv->ncleanupCallbacks - (i + 1)])
2889 2890 2891 2892 2893 2894 2895
            priv->cleanupCallbacks[i](driver, vm);
    }

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

2897 2898 2899
static void
qemuDomainGetImageIds(virQEMUDriverConfigPtr cfg,
                      virDomainObjPtr vm,
2900
                      virStorageSourcePtr src,
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
                      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;
    }

2919 2920
    if (vm && (vmlabel = virDomainDefGetSecurityLabelDef(vm->def, "dac")) &&
        vmlabel->label)
2921 2922
        virParseOwnershipIds(vmlabel->label, uid, gid);

2923
    if ((disklabel = virStorageSourceGetSecurityLabelDef(src, "dac")) &&
2924
        disklabel->label)
2925 2926 2927 2928
        virParseOwnershipIds(disklabel->label, uid, gid);
}


2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
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;
}


2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
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;
}


2968
int
2969
qemuDomainDetermineDiskChain(virQEMUDriverPtr driver,
2970
                             virDomainObjPtr vm,
2971
                             virDomainDiskDefPtr disk,
2972 2973
                             bool force_probe,
                             bool report_broken)
2974
{
2975 2976
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    int ret = 0;
2977 2978
    uid_t uid;
    gid_t gid;
2979

2980
    if (virStorageSourceIsEmpty(disk->src))
2981
        goto cleanup;
2982

2983
    if (disk->src->backingStore) {
2984
        if (force_probe)
2985
            virStorageSourceBackingStoreClear(disk->src);
2986
        else
2987
            goto cleanup;
2988
    }
2989

2990
    qemuDomainGetImageIds(cfg, vm, disk->src, &uid, &gid);
2991

2992
    if (virStorageFileGetMetadata(disk->src,
2993
                                  uid, gid,
2994
                                  cfg->allowDiskFormatProbing,
2995
                                  report_broken) < 0)
2996 2997
        ret = -1;

2998
 cleanup:
2999 3000
    virObjectUnref(cfg);
    return ret;
3001
}
3002

3003

3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
bool
qemuDomainDiskSourceDiffers(virConnectPtr conn,
                            virDomainDiskDefPtr disk,
                            virDomainDiskDefPtr origDisk)
{
    char *diskSrc = NULL, *origDiskSrc = NULL;
    bool diskEmpty, origDiskEmpty;
    bool ret = true;

    diskEmpty = virStorageSourceIsEmpty(disk->src);
    origDiskEmpty = virStorageSourceIsEmpty(origDisk->src);

    if (diskEmpty && origDiskEmpty)
        return false;

    if (diskEmpty ^ origDiskEmpty)
        return true;

    if (qemuGetDriveSourceString(disk->src, conn, &diskSrc) < 0 ||
        qemuGetDriveSourceString(origDisk->src, conn, &origDiskSrc) < 0)
        goto cleanup;

    /* So far in qemu disk sources are considered different
     * if either path to disk or its format changes. */
    ret = virDomainDiskGetFormat(disk) != virDomainDiskGetFormat(origDisk) ||
          STRNEQ_NULLABLE(diskSrc, origDiskSrc);
 cleanup:
    VIR_FREE(diskSrc);
    VIR_FREE(origDiskSrc);
    return ret;
}


3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
/*
 * Makes sure the @disk differs from @orig_disk only by the source
 * path and nothing else.  Fields that are being checked and the
 * information whether they are nullable (may not be specified) or is
 * taken from the virDomainDiskDefFormat() code.
 */
bool
qemuDomainDiskChangeSupported(virDomainDiskDefPtr disk,
                              virDomainDiskDefPtr orig_disk)
{
#define CHECK_EQ(field, field_name, nullable)                           \
    do {                                                                \
        if (nullable && !disk->field)                                   \
            break;                                                      \
        if (disk->field != orig_disk->field) {                          \
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,               \
                           _("cannot modify field '%s' of the disk"),   \
                           field_name);                                 \
            return false;                                               \
        }                                                               \
    } while (0)

    CHECK_EQ(device, "device", false);
3060 3061 3062 3063 3064 3065 3066 3067 3068
    CHECK_EQ(bus, "bus", false);
    if (STRNEQ(disk->dst, orig_disk->dst)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
                       "bus");
        return false;
    }
    CHECK_EQ(tray_status, "tray", true);
    CHECK_EQ(removable, "removable", true);
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151

    if (disk->geometry.cylinders &&
        disk->geometry.heads &&
        disk->geometry.sectors) {
        CHECK_EQ(geometry.cylinders, "geometry cylinders", false);
        CHECK_EQ(geometry.heads, "geometry heads", false);
        CHECK_EQ(geometry.sectors, "geometry sectors", false);
        CHECK_EQ(geometry.trans, "BIOS-translation-modus", true);
    }

    CHECK_EQ(blockio.logical_block_size,
             "blockio logical_block_size", false);
    CHECK_EQ(blockio.physical_block_size,
             "blockio physical_block_size", false);

    CHECK_EQ(blkdeviotune.total_bytes_sec,
             "blkdeviotune total_bytes_sec",
             true);
    CHECK_EQ(blkdeviotune.read_bytes_sec,
             "blkdeviotune read_bytes_sec",
             true);
    CHECK_EQ(blkdeviotune.write_bytes_sec,
             "blkdeviotune write_bytes_sec",
             true);
    CHECK_EQ(blkdeviotune.total_iops_sec,
             "blkdeviotune total_iops_sec",
             true);
    CHECK_EQ(blkdeviotune.read_iops_sec,
             "blkdeviotune read_iops_sec",
             true);
    CHECK_EQ(blkdeviotune.write_iops_sec,
             "blkdeviotune write_iops_sec",
             true);
    CHECK_EQ(blkdeviotune.total_bytes_sec_max,
             "blkdeviotune total_bytes_sec_max",
             true);
    CHECK_EQ(blkdeviotune.read_bytes_sec_max,
             "blkdeviotune read_bytes_sec_max",
             true);
    CHECK_EQ(blkdeviotune.write_bytes_sec_max,
             "blkdeviotune write_bytes_sec_max",
             true);
    CHECK_EQ(blkdeviotune.total_iops_sec_max,
             "blkdeviotune total_iops_sec_max",
             true);
    CHECK_EQ(blkdeviotune.read_iops_sec_max,
             "blkdeviotune read_iops_sec_max",
             true);
    CHECK_EQ(blkdeviotune.write_iops_sec_max,
             "blkdeviotune write_iops_sec_max",
             true);
    CHECK_EQ(blkdeviotune.size_iops_sec,
             "blkdeviotune size_iops_sec",
             true);

    if (disk->serial && STRNEQ_NULLABLE(disk->serial, orig_disk->serial)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
                       "serial");
        return false;
    }

    if (disk->wwn && STRNEQ_NULLABLE(disk->wwn, orig_disk->wwn)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
                       "wwn");
        return false;
    }

    if (disk->vendor && STRNEQ_NULLABLE(disk->vendor, orig_disk->vendor)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
                       "vendor");
        return false;
    }

    if (disk->product && STRNEQ_NULLABLE(disk->product, orig_disk->product)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
                       "product");
        return false;
    }

3152 3153 3154 3155 3156 3157 3158 3159
    CHECK_EQ(cachemode, "cache", true);
    CHECK_EQ(error_policy, "error_policy", true);
    CHECK_EQ(rerror_policy, "rerror_policy", true);
    CHECK_EQ(iomode, "io", true);
    CHECK_EQ(ioeventfd, "ioeventfd", true);
    CHECK_EQ(event_idx, "event_idx", true);
    CHECK_EQ(copy_on_read, "copy_on_read", true);
    CHECK_EQ(snapshot, "snapshot", true);
3160
    /* startupPolicy is allowed to be updated. Therefore not checked here. */
3161
    CHECK_EQ(transient, "transient", true);
3162
    CHECK_EQ(info.bootIndex, "boot order", true);
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
    CHECK_EQ(rawio, "rawio", true);
    CHECK_EQ(sgio, "sgio", true);
    CHECK_EQ(discard, "discard", true);
    CHECK_EQ(iothread, "iothread", true);

    if (disk->domain_name &&
        STRNEQ_NULLABLE(disk->domain_name, orig_disk->domain_name)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
                       "backenddomain");
        return false;
    }
3175 3176 3177 3178 3179 3180

#undef CHECK_EQ

    return true;
}

3181 3182 3183
bool
qemuDomainDiskBlockJobIsActive(virDomainDiskDefPtr disk)
{
3184 3185
    qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

3186 3187 3188 3189 3190 3191 3192 3193
    if (disk->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' already in active block job"),
                       disk->dst);

        return true;
    }

3194
    if (diskPriv->blockjob) {
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("disk '%s' already in active block job"),
                       disk->dst);
        return true;
    }

    return false;
}


3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
/**
 * qemuDomainHasBlockjob:
 * @vm: domain object
 * @copy_only: Reject only block copy job
 *
 * Return true if @vm has at least one disk involved in a current block
 * copy/commit/pull job. If @copy_only is true this returns true only if the
 * disk is involved in a block copy.
 * */
bool
qemuDomainHasBlockjob(virDomainObjPtr vm,
                      bool copy_only)
{
    size_t i;
    for (i = 0; i < vm->def->ndisks; i++) {
3220 3221 3222 3223
        virDomainDiskDefPtr disk = vm->def->disks[i];
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

        if (!copy_only && diskPriv->blockjob)
3224 3225
            return true;

3226
        if (disk->mirror && disk->mirrorJob == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY)
3227 3228 3229 3230 3231 3232 3233
            return true;
    }

    return false;
}


3234 3235
int
qemuDomainUpdateDeviceList(virQEMUDriverPtr driver,
3236 3237
                           virDomainObjPtr vm,
                           int asyncJob)
3238 3239 3240
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char **aliases;
3241
    int rc;
3242 3243 3244 3245

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

3246 3247
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;
3248 3249 3250 3251
    rc = qemuMonitorGetDeviceAliases(priv->mon, &aliases);
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return -1;
    if (rc < 0)
3252 3253 3254 3255 3256 3257
        return -1;

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

3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307

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


3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323
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);

3324
 cleanup:
3325 3326 3327 3328
    virDomainDefFree(migratableDefSrc);
    virDomainDefFree(migratableDefDst);
    return ret;
}
3329 3330

bool
3331
qemuDomainAgentAvailable(virDomainObjPtr vm,
3332 3333
                         bool reportError)
{
3334 3335
    qemuDomainObjPrivatePtr priv = vm->privateData;

3336 3337 3338 3339 3340 3341 3342
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_RUNNING) {
        if (reportError) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain is not running"));
        }
        return false;
    }
3343 3344 3345 3346 3347 3348 3349 3350 3351
    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) {
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
        if (qemuFindAgentConfig(vm->def)) {
            if (reportError) {
                virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                               _("QEMU guest agent is not connected"));
            }
            return false;
        } else {
            if (reportError) {
                virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                               _("QEMU guest agent is not configured"));
            }
            return false;
3364 3365 3366 3367
        }
    }
    return true;
}
3368

3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386

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

3387 3388 3389 3390
    /* 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);

3391 3392 3393 3394
    /* Align memory module sizes */
    for (i = 0; i < def->nmems; i++)
        qemuDomainMemoryDeviceAlignSize(def->mems[i]);

3395 3396
    return 0;
}
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411


/**
 * 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);
}
3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424


/**
 * qemuDomainGetMonitor:
 * @vm: domain object
 *
 * Returns the monitor pointer corresponding to the domain object @vm.
 */
qemuMonitorPtr
qemuDomainGetMonitor(virDomainObjPtr vm)
{
    return ((qemuDomainObjPrivatePtr) vm->privateData)->mon;
}
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440


/**
 * qemuDomainSupportsBlockJobs:
 * @vm: domain object
 * @modern: pointer to bool that returns whether modern block jobs are supported
 *
 * Returns -1 in case when qemu does not support block jobs at all. Otherwise
 * returns 0 and optionally fills @modern to denote that modern (async) block
 * jobs are supported.
 */
int
qemuDomainSupportsBlockJobs(virDomainObjPtr vm,
                            bool *modern)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3441 3442
    bool asynchronous = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_ASYNC);
    bool synchronous = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_SYNC);
3443

3444
    if (!synchronous && !asynchronous) {
3445 3446 3447 3448 3449 3450
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block jobs not supported with this QEMU binary"));
        return -1;
    }

    if (modern)
3451
        *modern = asynchronous;
3452 3453 3454

    return 0;
}
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483


/**
 * qemuFindAgentConfig:
 * @def: domain definition
 *
 * Returns the pointer to the channel definition that is used to access the
 * guest agent if the agent is configured or NULL otherwise.
 */
virDomainChrSourceDefPtr
qemuFindAgentConfig(virDomainDefPtr def)
{
    virDomainChrSourceDefPtr config = NULL;
    size_t i;

    for (i = 0; i < def->nchannels; i++) {
        virDomainChrDefPtr channel = def->channels[i];

        if (channel->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO)
            continue;

        if (STREQ_NULLABLE(channel->target.name, "org.qemu.guest_agent.0")) {
            config = &channel->source;
            break;
        }
    }

    return config;
}
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502


bool
qemuDomainMachineIsQ35(const virDomainDef *def)
{
    return (STRPREFIX(def->os.machine, "pc-q35") ||
            STREQ(def->os.machine, "q35"));
}


bool
qemuDomainMachineIsI440FX(const virDomainDef *def)
{
    return (STREQ(def->os.machine, "pc") ||
            STRPREFIX(def->os.machine, "pc-0.") ||
            STRPREFIX(def->os.machine, "pc-1.") ||
            STRPREFIX(def->os.machine, "pc-i440") ||
            STRPREFIX(def->os.machine, "rhel"));
}
3503 3504


3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
bool
qemuDomainMachineNeedsFDC(const virDomainDef *def)
{
    char *p = STRSKIP(def->os.machine, "pc-q35-");

    if (p) {
        if (STRPREFIX(p, "1.") ||
            STRPREFIX(p, "2.0") ||
            STRPREFIX(p, "2.1") ||
            STRPREFIX(p, "2.2") ||
            STRPREFIX(p, "2.3"))
            return false;
        return true;
    }
    return false;
}


3523 3524 3525 3526 3527 3528
bool
qemuDomainMachineIsS390CCW(const virDomainDef *def)
{
    return STRPREFIX(def->os.machine, "s390-ccw");
}

3529

3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
/**
 * qemuDomainUpdateCurrentMemorySize:
 *
 * Updates the current balloon size from the monitor if necessary. In case when
 * the balloon is not present for the domain, the function recalculates the
 * maximum size to reflect possible changes.
 *
 * Returns 0 on success and updates vm->def->mem.cur_balloon if necessary, -1 on
 * error and reports libvirt error.
 */
int
qemuDomainUpdateCurrentMemorySize(virQEMUDriverPtr driver,
                                  virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    unsigned long long balloon;
    int ret = -1;

    /* inactive domain doesn't need size update */
    if (!virDomainObjIsActive(vm))
        return 0;

    /* if no balloning is available, the current size equals to the current
     * full memory size */
    if (!vm->def->memballoon ||
        vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE) {
        vm->def->mem.cur_balloon = virDomainDefGetMemoryActual(vm->def);
        return 0;
    }

    /* current size is always automagically updated via the event */
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BALLOON_EVENT))
        return 0;

    /* here we need to ask the monitor */

    /* Don't delay if someone's using the monitor, just use existing most
     * recent data instead */
    if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            return -1;

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

        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
        if (qemuDomainObjExitMonitor(driver, vm) < 0)
            ret = -1;

 endjob:
        qemuDomainObjEndJob(driver, vm);

        if (ret < 0)
            return -1;

3589 3590
        vm->def->mem.cur_balloon = balloon;
    }
3591 3592 3593

    return 0;
}