qemu_domain.c 170.9 KB
Newer Older
1
/*
2
 * qemu_domain.c: QEMU domain private state
3
 *
4
 * Copyright (C) 2006-2016 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
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include "qemu_domain.h"
J
John Ferlan 已提交
27
#include "qemu_alias.h"
28
#include "qemu_cgroup.h"
29
#include "qemu_command.h"
30
#include "qemu_parse_command.h"
31
#include "qemu_capabilities.h"
32
#include "qemu_migration.h"
33
#include "viralloc.h"
34
#include "virlog.h"
35
#include "virerror.h"
36
#include "c-ctype.h"
37
#include "cpu/cpu.h"
38
#include "viruuid.h"
E
Eric Blake 已提交
39
#include "virfile.h"
40
#include "domain_addr.h"
41
#include "domain_event.h"
42
#include "virtime.h"
43
#include "virstoragefile.h"
44
#include "virstring.h"
45
#include "virthreadjob.h"
46
#include "viratomic.h"
47
#include "virprocess.h"
48
#include "vircrypto.h"
49
#include "secret_util.h"
50
#include "logging/log_manager.h"
51
#include "locking/domain_lock.h"
52

53 54
#include "storage/storage_driver.h"

55
#include <sys/time.h>
56
#include <fcntl.h>
57

58 59 60 61
#include <libxml/xpathInternals.h>

#define VIR_FROM_THIS VIR_FROM_QEMU

62 63
VIR_LOG_INIT("qemu.qemu_domain");

64 65
#define QEMU_NAMESPACE_HREF "http://libvirt.org/schemas/domain/qemu/1.0"

66 67 68 69 70 71
VIR_ENUM_IMPL(qemuDomainJob, QEMU_JOB_LAST,
              "none",
              "query",
              "destroy",
              "suspend",
              "modify",
72
              "abort",
73
              "migration operation",
74 75 76 77 78 79 80 81 82 83
              "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",
84
              "snapshot",
85
              "start",
86 87
);

88

89 90 91
struct _qemuDomainLogContext {
    int refs;
    int writefd;
92
    int readfd; /* Only used if manager == NULL */
93
    off_t pos;
94
    ino_t inode; /* Only used if manager != NULL */
95
    char *path;
96
    virLogManagerPtr manager;
97 98
};

J
Jiri Denemark 已提交
99
const char *
100
qemuDomainAsyncJobPhaseToString(qemuDomainAsyncJob job,
J
Jiri Denemark 已提交
101 102 103 104 105
                                int phase ATTRIBUTE_UNUSED)
{
    switch (job) {
    case QEMU_ASYNC_JOB_MIGRATION_OUT:
    case QEMU_ASYNC_JOB_MIGRATION_IN:
106 107
        return qemuMigrationJobPhaseTypeToString(phase);

J
Jiri Denemark 已提交
108 109
    case QEMU_ASYNC_JOB_SAVE:
    case QEMU_ASYNC_JOB_DUMP:
110
    case QEMU_ASYNC_JOB_SNAPSHOT:
111
    case QEMU_ASYNC_JOB_START:
J
Jiri Denemark 已提交
112 113 114 115 116 117 118 119 120
    case QEMU_ASYNC_JOB_NONE:
    case QEMU_ASYNC_JOB_LAST:
        ; /* fall through */
    }

    return "none";
}

int
121
qemuDomainAsyncJobPhaseFromString(qemuDomainAsyncJob job,
J
Jiri Denemark 已提交
122 123 124 125 126 127 128 129
                                  const char *phase)
{
    if (!phase)
        return 0;

    switch (job) {
    case QEMU_ASYNC_JOB_MIGRATION_OUT:
    case QEMU_ASYNC_JOB_MIGRATION_IN:
130 131
        return qemuMigrationJobPhaseTypeFromString(phase);

J
Jiri Denemark 已提交
132 133
    case QEMU_ASYNC_JOB_SAVE:
    case QEMU_ASYNC_JOB_DUMP:
134
    case QEMU_ASYNC_JOB_SNAPSHOT:
135
    case QEMU_ASYNC_JOB_START:
J
Jiri Denemark 已提交
136 137 138 139 140 141 142 143 144 145 146
    case QEMU_ASYNC_JOB_NONE:
    case QEMU_ASYNC_JOB_LAST:
        ; /* fall through */
    }

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

147

148
void qemuDomainEventQueue(virQEMUDriverPtr driver,
149
                          virObjectEventPtr event)
150
{
151 152
    if (event)
        virObjectEventStateQueue(driver->domainEventState, event);
153 154 155
}


156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
void
qemuDomainEventEmitJobCompleted(virQEMUDriverPtr driver,
                                virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virObjectEventPtr event;
    virTypedParameterPtr params = NULL;
    int nparams = 0;
    int type;

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

    if (qemuDomainJobInfoToParams(priv->job.completed, &type,
                                  &params, &nparams) < 0) {
        VIR_WARN("Could not get stats for completed job; domain %s",
                 vm->def->name);
    }

    event = virDomainEventJobCompletedNewFromObj(vm, params, nparams);
    qemuDomainEventQueue(driver, event);
}


180 181 182 183 184 185 186 187
static int
qemuDomainObjInitJob(qemuDomainObjPrivatePtr priv)
{
    memset(&priv->job, 0, sizeof(priv->job));

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

188
    if (virCondInit(&priv->job.asyncCond) < 0) {
189
        virCondDestroy(&priv->job.cond);
190 191 192
        return -1;
    }

193 194 195 196 197 198 199 200 201
    return 0;
}

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

    job->active = QEMU_JOB_NONE;
202
    job->owner = 0;
203
    job->ownerAPI = NULL;
J
Jiri Denemark 已提交
204
    job->started = 0;
205 206 207 208 209 210 211 212
}

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

    job->asyncJob = QEMU_ASYNC_JOB_NONE;
213
    job->asyncOwner = 0;
214
    job->asyncOwnerAPI = NULL;
J
Jiri Denemark 已提交
215
    job->asyncStarted = 0;
J
Jiri Denemark 已提交
216
    job->phase = 0;
217
    job->mask = QEMU_JOB_DEFAULT_MASK;
218
    job->dump_memory_only = false;
219
    job->abortJob = false;
220
    job->spiceMigrated = false;
221
    job->postcopyEnabled = false;
J
Jiri Denemark 已提交
222
    VIR_FREE(job->current);
223 224
}

225 226 227 228 229 230 231 232
void
qemuDomainObjRestoreJob(virDomainObjPtr obj,
                        struct qemuDomainJobObj *job)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    memset(job, 0, sizeof(*job));
    job->active = priv->job.active;
233
    job->owner = priv->job.owner;
234
    job->asyncJob = priv->job.asyncJob;
235
    job->asyncOwner = priv->job.asyncOwner;
J
Jiri Denemark 已提交
236
    job->phase = priv->job.phase;
237 238 239 240 241

    qemuDomainObjResetJob(priv);
    qemuDomainObjResetAsyncJob(priv);
}

242 243 244
static void
qemuDomainObjFreeJob(qemuDomainObjPrivatePtr priv)
{
J
Jiri Denemark 已提交
245
    VIR_FREE(priv->job.current);
246
    VIR_FREE(priv->job.completed);
247 248
    virCondDestroy(&priv->job.cond);
    virCondDestroy(&priv->job.asyncCond);
249 250
}

251
static bool
252
qemuDomainTrackJob(qemuDomainJob job)
253 254 255 256
{
    return (QEMU_DOMAIN_TRACK_JOBS & JOB_MASK(job)) != 0;
}

257

J
Jiri Denemark 已提交
258 259 260 261 262 263 264 265 266 267 268
int
qemuDomainJobInfoUpdateTime(qemuDomainJobInfoPtr jobInfo)
{
    unsigned long long now;

    if (!jobInfo->started)
        return 0;

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

269 270 271 272 273 274
    if (now < jobInfo->started) {
        VIR_WARN("Async job starts in the future");
        jobInfo->started = 0;
        return 0;
    }

J
Jiri Denemark 已提交
275 276 277 278
    jobInfo->timeElapsed = now - jobInfo->started;
    return 0;
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
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;
    }

296 297
    jobInfo->stats.downtime = now - jobInfo->stopped;
    jobInfo->stats.downtime_set = true;
298 299 300
    return 0;
}

J
Jiri Denemark 已提交
301 302 303 304
int
qemuDomainJobInfoToInfo(qemuDomainJobInfoPtr jobInfo,
                        virDomainJobInfoPtr info)
{
305
    info->type = jobInfo->type;
J
Jiri Denemark 已提交
306 307 308
    info->timeElapsed = jobInfo->timeElapsed;
    info->timeRemaining = jobInfo->timeRemaining;

309 310 311
    info->memTotal = jobInfo->stats.ram_total;
    info->memRemaining = jobInfo->stats.ram_remaining;
    info->memProcessed = jobInfo->stats.ram_transferred;
J
Jiri Denemark 已提交
312

313 314 315
    info->fileTotal = jobInfo->stats.disk_total;
    info->fileRemaining = jobInfo->stats.disk_remaining;
    info->fileProcessed = jobInfo->stats.disk_transferred;
J
Jiri Denemark 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329

    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)
{
330
    qemuMonitorMigrationStats *stats = &jobInfo->stats;
J
Jiri Denemark 已提交
331 332 333 334 335 336 337 338 339
    virTypedParameterPtr par = NULL;
    int maxpar = 0;
    int npar = 0;

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

340 341 342 343 344 345 346
    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 已提交
347 348 349 350 351 352
    if (jobInfo->type == VIR_DOMAIN_JOB_BOUNDED &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_TIME_REMAINING,
                                jobInfo->timeRemaining) < 0)
        goto error;

353
    if (stats->downtime_set &&
J
Jiri Denemark 已提交
354 355
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DOWNTIME,
356
                                stats->downtime) < 0)
J
Jiri Denemark 已提交
357 358
        goto error;

359
    if (stats->downtime_set &&
360
        jobInfo->timeDeltaSet &&
361
        stats->downtime > jobInfo->timeDelta &&
362 363
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DOWNTIME_NET,
364
                                stats->downtime - jobInfo->timeDelta) < 0)
365 366
        goto error;

367
    if (stats->setup_time_set &&
368 369
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_SETUP_TIME,
370
                                stats->setup_time) < 0)
371 372
        goto error;

J
Jiri Denemark 已提交
373 374
    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_TOTAL,
375 376
                                stats->ram_total +
                                stats->disk_total) < 0 ||
J
Jiri Denemark 已提交
377 378
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_PROCESSED,
379 380
                                stats->ram_transferred +
                                stats->disk_transferred) < 0 ||
J
Jiri Denemark 已提交
381 382
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_REMAINING,
383 384
                                stats->ram_remaining +
                                stats->disk_remaining) < 0)
J
Jiri Denemark 已提交
385 386 387 388
        goto error;

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_TOTAL,
389
                                stats->ram_total) < 0 ||
J
Jiri Denemark 已提交
390 391
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_PROCESSED,
392
                                stats->ram_transferred) < 0 ||
J
Jiri Denemark 已提交
393 394
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_REMAINING,
395
                                stats->ram_remaining) < 0)
J
Jiri Denemark 已提交
396 397
        goto error;

398
    if (stats->ram_bps &&
399 400
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_BPS,
401
                                stats->ram_bps) < 0)
402 403
        goto error;

404
    if (stats->ram_duplicate_set) {
J
Jiri Denemark 已提交
405 406
        if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_CONSTANT,
407
                                    stats->ram_duplicate) < 0 ||
J
Jiri Denemark 已提交
408 409
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_NORMAL,
410
                                    stats->ram_normal) < 0 ||
J
Jiri Denemark 已提交
411 412
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES,
413
                                    stats->ram_normal_bytes) < 0)
J
Jiri Denemark 已提交
414 415 416
            goto error;
    }

417 418 419 420 421 422 423 424
    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_DIRTY_RATE,
                                stats->ram_dirty_rate) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_ITERATION,
                                stats->ram_iteration) < 0)
        goto error;

J
Jiri Denemark 已提交
425 426
    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_TOTAL,
427
                                stats->disk_total) < 0 ||
J
Jiri Denemark 已提交
428 429
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_PROCESSED,
430
                                stats->disk_transferred) < 0 ||
J
Jiri Denemark 已提交
431 432
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_REMAINING,
433
                                stats->disk_remaining) < 0)
J
Jiri Denemark 已提交
434 435
        goto error;

436
    if (stats->disk_bps &&
437 438
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_BPS,
439
                                stats->disk_bps) < 0)
440 441
        goto error;

442
    if (stats->xbzrle_set) {
J
Jiri Denemark 已提交
443 444
        if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_CACHE,
445
                                    stats->xbzrle_cache_size) < 0 ||
J
Jiri Denemark 已提交
446 447
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_BYTES,
448
                                    stats->xbzrle_bytes) < 0 ||
J
Jiri Denemark 已提交
449 450
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_PAGES,
451
                                    stats->xbzrle_pages) < 0 ||
J
Jiri Denemark 已提交
452 453
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_CACHE_MISSES,
454
                                    stats->xbzrle_cache_miss) < 0 ||
J
Jiri Denemark 已提交
455 456
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_OVERFLOW,
457
                                    stats->xbzrle_overflow) < 0)
J
Jiri Denemark 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471
            goto error;
    }

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

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


J
John Ferlan 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
/* qemuDomainGetMasterKeyFilePath:
 * @libDir: Directory path to domain lib files
 *
 * Generate a path to the domain master key file for libDir.
 * It's up to the caller to handle checking if path exists.
 *
 * Returns path to memory containing the name of the file. It is up to the
 * caller to free; otherwise, NULL on failure.
 */
char *
qemuDomainGetMasterKeyFilePath(const char *libDir)
{
    if (!libDir) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid path for master key file"));
        return NULL;
    }
    return virFileBuildPath(libDir, "master-key.aes", NULL);
}


/* qemuDomainWriteMasterKeyFile:
494 495
 * @driver: qemu driver data
 * @vm: Pointer to the vm object
J
John Ferlan 已提交
496 497 498 499 500
 *
 * Get the desired path to the masterKey file and store it in the path.
 *
 * Returns 0 on success, -1 on failure with error message indicating failure
 */
501
int
M
Martin Kletzander 已提交
502 503
qemuDomainWriteMasterKeyFile(virQEMUDriverPtr driver,
                             virDomainObjPtr vm)
J
John Ferlan 已提交
504 505 506 507
{
    char *path;
    int fd = -1;
    int ret = -1;
M
Martin Kletzander 已提交
508
    qemuDomainObjPrivatePtr priv = vm->privateData;
J
John Ferlan 已提交
509

510 511 512 513
    /* Only gets filled in if we have the capability */
    if (!priv->masterKey)
        return 0;

J
John Ferlan 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    if (!(path = qemuDomainGetMasterKeyFilePath(priv->libDir)))
        return -1;

    if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0600)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to open domain master key file for write"));
        goto cleanup;
    }

    if (safewrite(fd, priv->masterKey, priv->masterKeyLen) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to write master key file for domain"));
        goto cleanup;
    }

529 530
    if (virSecurityManagerDomainSetPathLabel(driver->securityManager,
                                             vm->def, path) < 0)
M
Martin Kletzander 已提交
531 532
        goto cleanup;

J
John Ferlan 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    ret = 0;

 cleanup:
    VIR_FORCE_CLOSE(fd);
    VIR_FREE(path);

    return ret;
}


/* qemuDomainMasterKeyReadFile:
 * @priv: pointer to domain private object
 *
 * Expected to be called during qemuProcessReconnect once the domain
 * libDir has been generated through qemuStateInitialize calling
 * virDomainObjListLoadAllConfigs which will restore the libDir path
 * to the domain private object.
 *
 * This function will get the path to the master key file and if it
 * exists, it will read the contents of the file saving it in priv->masterKey.
 *
 * Once the file exists, the validity checks may cause failures; however,
 * if the file doesn't exist or the capability doesn't exist, we just
 * return (mostly) quietly.
 *
 * Returns 0 on success or lack of capability
 *        -1 on failure with error message indicating failure
 */
int
qemuDomainMasterKeyReadFile(qemuDomainObjPrivatePtr priv)
{
    char *path;
    int fd = -1;
    uint8_t *masterKey = NULL;
    ssize_t masterKeyLen = 0;

    /* If we don't have the capability, then do nothing. */
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET))
        return 0;

    if (!(path = qemuDomainGetMasterKeyFilePath(priv->libDir)))
        return -1;

    if (!virFileExists(path)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("domain master key file doesn't exist in %s"),
                       priv->libDir);
        goto error;
    }

    if ((fd = open(path, O_RDONLY)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to open domain master key file for read"));
        goto error;
    }

    if (VIR_ALLOC_N(masterKey, 1024) < 0)
        goto error;

    if ((masterKeyLen = saferead(fd, masterKey, 1024)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unable to read domain master key file"));
        goto error;
    }

    if (masterKeyLen != QEMU_DOMAIN_MASTER_KEY_LEN) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid master key read, size=%zd"), masterKeyLen);
        goto error;
    }

    ignore_value(VIR_REALLOC_N_QUIET(masterKey, masterKeyLen));

    priv->masterKey = masterKey;
    priv->masterKeyLen = masterKeyLen;

    VIR_FORCE_CLOSE(fd);
    VIR_FREE(path);

    return 0;

 error:
    if (masterKeyLen > 0)
        memset(masterKey, 0, masterKeyLen);
    VIR_FREE(masterKey);

    VIR_FORCE_CLOSE(fd);
    VIR_FREE(path);

    return -1;
}


/* qemuDomainMasterKeyRemove:
 * @priv: Pointer to the domain private object
 *
 * Remove the traces of the master key, clear the heap, clear the file,
 * delete the file.
 */
void
qemuDomainMasterKeyRemove(qemuDomainObjPrivatePtr priv)
{
    char *path = NULL;

    if (!priv->masterKey)
        return;

    /* Clear the contents */
    memset(priv->masterKey, 0, priv->masterKeyLen);
    VIR_FREE(priv->masterKey);
    priv->masterKeyLen = 0;

    /* Delete the master key file */
    path = qemuDomainGetMasterKeyFilePath(priv->libDir);
    unlink(path);

    VIR_FREE(path);
}


/* qemuDomainMasterKeyCreate:
654
 * @vm: Pointer to the domain object
J
John Ferlan 已提交
655 656 657 658 659 660 661 662
 *
 * As long as the underlying qemu has the secret capability,
 * generate and store 'raw' in a file a random 32-byte key to
 * be used as a secret shared with qemu to share sensitive data.
 *
 * Returns: 0 on success, -1 w/ error message on failure
 */
int
663
qemuDomainMasterKeyCreate(virDomainObjPtr vm)
J
John Ferlan 已提交
664
{
M
Martin Kletzander 已提交
665 666
    qemuDomainObjPrivatePtr priv = vm->privateData;

J
John Ferlan 已提交
667 668 669 670 671
    /* If we don't have the capability, then do nothing. */
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET))
        return 0;

    if (!(priv->masterKey =
672
          virCryptoGenerateRandom(QEMU_DOMAIN_MASTER_KEY_LEN)))
673
        return -1;
J
John Ferlan 已提交
674 675 676 677 678 679 680

    priv->masterKeyLen = QEMU_DOMAIN_MASTER_KEY_LEN;

    return 0;
}


681
static void
682
qemuDomainSecretPlainClear(qemuDomainSecretPlain secret)
683 684
{
    VIR_FREE(secret.username);
685
    VIR_DISPOSE_N(secret.secret, secret.secretlen);
686 687 688
}


J
John Ferlan 已提交
689
static void
690
qemuDomainSecretAESClear(qemuDomainSecretAES secret)
J
John Ferlan 已提交
691 692 693 694 695 696 697 698
{
    VIR_FREE(secret.username);
    VIR_FREE(secret.alias);
    VIR_FREE(secret.iv);
    VIR_FREE(secret.ciphertext);
}


699 700 701 702 703 704
static void
qemuDomainSecretInfoFree(qemuDomainSecretInfoPtr *secinfo)
{
    if (!*secinfo)
        return;

J
John Ferlan 已提交
705 706
    switch ((qemuDomainSecretInfoType) (*secinfo)->type) {
    case VIR_DOMAIN_SECRET_INFO_TYPE_PLAIN:
707
        qemuDomainSecretPlainClear((*secinfo)->s.plain);
J
John Ferlan 已提交
708 709
        break;

710
    case VIR_DOMAIN_SECRET_INFO_TYPE_AES:
711
        qemuDomainSecretAESClear((*secinfo)->s.aes);
J
John Ferlan 已提交
712 713 714 715 716 717
        break;

    case VIR_DOMAIN_SECRET_INFO_TYPE_LAST:
        break;
    }

718 719 720 721
    VIR_FREE(*secinfo);
}


722
static virClassPtr qemuDomainDiskPrivateClass;
723
static void qemuDomainDiskPrivateDispose(void *obj);
724 725 726 727 728 729 730

static int
qemuDomainDiskPrivateOnceInit(void)
{
    qemuDomainDiskPrivateClass = virClassNew(virClassForObject(),
                                             "qemuDomainDiskPrivate",
                                             sizeof(qemuDomainDiskPrivate),
731
                                             qemuDomainDiskPrivateDispose);
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    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;
}


755 756 757 758 759 760 761 762 763
static void
qemuDomainDiskPrivateDispose(void *obj)
{
    qemuDomainDiskPrivatePtr priv = obj;

    qemuDomainSecretInfoFree(&priv->secinfo);
}


764 765 766 767 768 769 770 771 772 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 798 799 800 801 802 803 804 805 806
static virClassPtr qemuDomainHostdevPrivateClass;
static void qemuDomainHostdevPrivateDispose(void *obj);

static int
qemuDomainHostdevPrivateOnceInit(void)
{
    qemuDomainHostdevPrivateClass =
        virClassNew(virClassForObject(),
                    "qemuDomainHostdevPrivate",
                    sizeof(qemuDomainHostdevPrivate),
                    qemuDomainHostdevPrivateDispose);
    if (!qemuDomainHostdevPrivateClass)
        return -1;
    else
        return 0;
}

VIR_ONCE_GLOBAL_INIT(qemuDomainHostdevPrivate)

static virObjectPtr
qemuDomainHostdevPrivateNew(void)
{
    qemuDomainHostdevPrivatePtr priv;

    if (qemuDomainHostdevPrivateInitialize() < 0)
        return NULL;

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

    return (virObjectPtr) priv;
}


static void
qemuDomainHostdevPrivateDispose(void *obj)
{
    qemuDomainHostdevPrivatePtr priv = obj;

    qemuDomainSecretInfoFree(&priv->secinfo);
}


807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
/* qemuDomainSecretPlainSetup:
 * @conn: Pointer to connection
 * @secinfo: Pointer to secret info
 * @protocol: Protocol for secret
 * @authdef: Pointer to auth data
 *
 * Taking a secinfo, fill in the plaintext information
 *
 * Returns 0 on success, -1 on failure with error message
 */
static int
qemuDomainSecretPlainSetup(virConnectPtr conn,
                           qemuDomainSecretInfoPtr secinfo,
                           virStorageNetProtocol protocol,
                           virStorageAuthDefPtr authdef)
{
    int secretType = VIR_SECRET_USAGE_TYPE_ISCSI;

825
    secinfo->type = VIR_DOMAIN_SECRET_INFO_TYPE_PLAIN;
826 827 828
    if (VIR_STRDUP(secinfo->s.plain.username, authdef->username) < 0)
        return -1;

829
    if (protocol == VIR_STORAGE_NET_PROTOCOL_RBD)
830 831
        secretType = VIR_SECRET_USAGE_TYPE_CEPH;

832 833 834
    return virSecretGetSecretString(conn, authdef, secretType,
                                    &secinfo->s.plain.secret,
                                    &secinfo->s.plain.secretlen);
835 836 837
}


838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
/* qemuDomainSecretAESSetup:
 * @conn: Pointer to connection
 * @priv: pointer to domain private object
 * @secinfo: Pointer to secret info
 * @srcalias: Alias of the disk/hostdev used to generate the secret alias
 * @protocol: Protocol for secret
 * @authdef: Pointer to auth data
 *
 * Taking a secinfo, fill in the AES specific information using the
 *
 * Returns 0 on success, -1 on failure with error message
 */
static int
qemuDomainSecretAESSetup(virConnectPtr conn,
                         qemuDomainObjPrivatePtr priv,
                         qemuDomainSecretInfoPtr secinfo,
                         const char *srcalias,
                         virStorageNetProtocol protocol,
                         virStorageAuthDefPtr authdef)
{
    int ret = -1;
    uint8_t *raw_iv = NULL;
    size_t ivlen = QEMU_DOMAIN_AES_IV_LEN;
    uint8_t *secret = NULL;
    size_t secretlen = 0;
    uint8_t *ciphertext = NULL;
    size_t ciphertextlen = 0;
    int secretType = VIR_SECRET_USAGE_TYPE_NONE;

    secinfo->type = VIR_DOMAIN_SECRET_INFO_TYPE_AES;
    if (VIR_STRDUP(secinfo->s.aes.username, authdef->username) < 0)
        return -1;

    switch ((virStorageNetProtocol)protocol) {
    case VIR_STORAGE_NET_PROTOCOL_RBD:
        secretType = VIR_SECRET_USAGE_TYPE_CEPH;
        break;

    case VIR_STORAGE_NET_PROTOCOL_NONE:
    case VIR_STORAGE_NET_PROTOCOL_NBD:
    case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
    case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
    case VIR_STORAGE_NET_PROTOCOL_ISCSI:
    case VIR_STORAGE_NET_PROTOCOL_HTTP:
    case VIR_STORAGE_NET_PROTOCOL_HTTPS:
    case VIR_STORAGE_NET_PROTOCOL_FTP:
    case VIR_STORAGE_NET_PROTOCOL_FTPS:
    case VIR_STORAGE_NET_PROTOCOL_TFTP:
    case VIR_STORAGE_NET_PROTOCOL_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("protocol '%s' cannot be used for encrypted secrets"),
                       virStorageNetProtocolTypeToString(protocol));
        return -1;
    }

    if (!(secinfo->s.aes.alias = qemuDomainGetSecretAESAlias(srcalias)))
        return -1;

    /* Create a random initialization vector */
    if (!(raw_iv = virCryptoGenerateRandom(ivlen)))
        return -1;

    /* Encode the IV and save that since qemu will need it */
    if (!(secinfo->s.aes.iv = virStringEncodeBase64(raw_iv, ivlen)))
        goto cleanup;

    /* Grab the unencoded secret */
    if (virSecretGetSecretString(conn, authdef, secretType,
                                 &secret, &secretlen) < 0)
        goto cleanup;

    if (virCryptoEncryptData(VIR_CRYPTO_CIPHER_AES256CBC,
                             priv->masterKey, QEMU_DOMAIN_MASTER_KEY_LEN,
                             raw_iv, ivlen, secret, secretlen,
                             &ciphertext, &ciphertextlen) < 0)
        goto cleanup;

    /* Clear out the secret */
    memset(secret, 0, secretlen);

    /* Now encode the ciphertext and store to be passed to qemu */
    if (!(secinfo->s.aes.ciphertext = virStringEncodeBase64(ciphertext,
                                                            ciphertextlen)))
        goto cleanup;

    ret = 0;

 cleanup:
    VIR_DISPOSE_N(raw_iv, ivlen);
    VIR_DISPOSE_N(secret, secretlen);
    VIR_DISPOSE_N(ciphertext, ciphertextlen);

    return ret;
}


934 935
/* qemuDomainSecretSetup:
 * @conn: Pointer to connection
936
 * @priv: pointer to domain private object
937
 * @secinfo: Pointer to secret info
938
 * @srcalias: Alias of the disk/hostdev used to generate the secret alias
939 940 941
 * @protocol: Protocol for secret
 * @authdef: Pointer to auth data
 *
942 943 944 945
 * If we have the encryption API present and can support a secret object, then
 * build the AES secret; otherwise, build the Plain secret. This is the magic
 * decision point for utilizing the AES secrets for an RBD disk. For now iSCSI
 * disks and hostdevs will not be able to utilize this mechanism.
946 947 948 949 950
 *
 * Returns 0 on success, -1 on failure
 */
static int
qemuDomainSecretSetup(virConnectPtr conn,
951
                      qemuDomainObjPrivatePtr priv,
952
                      qemuDomainSecretInfoPtr secinfo,
953
                      const char *srcalias,
954 955 956
                      virStorageNetProtocol protocol,
                      virStorageAuthDefPtr authdef)
{
957 958 959 960 961 962 963 964 965 966 967
    if (virCryptoHaveCipher(VIR_CRYPTO_CIPHER_AES256CBC) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET) &&
        protocol == VIR_STORAGE_NET_PROTOCOL_RBD) {
        if (qemuDomainSecretAESSetup(conn, priv, secinfo,
                                     srcalias, protocol, authdef) < 0)
            return -1;
    } else {
        if (qemuDomainSecretPlainSetup(conn, secinfo, protocol, authdef) < 0)
            return -1;
    }
    return 0;
968 969 970
}


971 972 973 974 975 976 977 978 979 980
/* qemuDomainSecretDiskDestroy:
 * @disk: Pointer to a disk definition
 *
 * Clear and destroy memory associated with the secret
 */
void
qemuDomainSecretDiskDestroy(virDomainDiskDefPtr disk)
{
    qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

981
    if (!diskPriv || !diskPriv->secinfo)
982 983 984 985 986 987 988 989
        return;

    qemuDomainSecretInfoFree(&diskPriv->secinfo);
}


/* qemuDomainSecretDiskPrepare:
 * @conn: Pointer to connection
J
John Ferlan 已提交
990
 * @priv: pointer to domain private object
991 992 993 994 995 996 997 998
 * @disk: Pointer to a disk definition
 *
 * For the right disk, generate the qemuDomainSecretInfo structure.
 *
 * Returns 0 on success, -1 on failure
 */
int
qemuDomainSecretDiskPrepare(virConnectPtr conn,
999
                            qemuDomainObjPrivatePtr priv,
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                            virDomainDiskDefPtr disk)
{
    virStorageSourcePtr src = disk->src;
    qemuDomainSecretInfoPtr secinfo = NULL;

    if (conn && !virStorageSourceIsEmpty(src) &&
        virStorageSourceGetActualType(src) == VIR_STORAGE_TYPE_NETWORK &&
        src->auth &&
        (src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI ||
         src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD)) {

        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

        if (VIR_ALLOC(secinfo) < 0)
            return -1;

1016 1017
        if (qemuDomainSecretSetup(conn, priv, secinfo, disk->info.alias,
                                  src->protocol, src->auth) < 0)
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
            goto error;

        diskPriv->secinfo = secinfo;
    }

    return 0;

 error:
    qemuDomainSecretInfoFree(&secinfo);
    return -1;
}


1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
/* qemuDomainSecretHostdevDestroy:
 * @disk: Pointer to a hostdev definition
 *
 * Clear and destroy memory associated with the secret
 */
void
qemuDomainSecretHostdevDestroy(virDomainHostdevDefPtr hostdev)
{
    qemuDomainHostdevPrivatePtr hostdevPriv =
        QEMU_DOMAIN_HOSTDEV_PRIVATE(hostdev);

1042
    if (!hostdevPriv || !hostdevPriv->secinfo)
1043 1044 1045 1046 1047 1048 1049 1050
        return;

    qemuDomainSecretInfoFree(&hostdevPriv->secinfo);
}


/* qemuDomainSecretHostdevPrepare:
 * @conn: Pointer to connection
J
John Ferlan 已提交
1051
 * @priv: pointer to domain private object
1052 1053 1054 1055 1056 1057 1058 1059
 * @hostdev: Pointer to a hostdev definition
 *
 * For the right host device, generate the qemuDomainSecretInfo structure.
 *
 * Returns 0 on success, -1 on failure
 */
int
qemuDomainSecretHostdevPrepare(virConnectPtr conn,
1060
                               qemuDomainObjPrivatePtr priv,
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
                               virDomainHostdevDefPtr hostdev)
{
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    qemuDomainSecretInfoPtr secinfo = NULL;

    if (conn && hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {

        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
        virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;

        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI &&
            iscsisrc->auth) {

            qemuDomainHostdevPrivatePtr hostdevPriv =
                QEMU_DOMAIN_HOSTDEV_PRIVATE(hostdev);

            if (VIR_ALLOC(secinfo) < 0)
                return -1;

1081
            if (qemuDomainSecretSetup(conn, priv, secinfo, hostdev->info->alias,
1082 1083
                                      VIR_STORAGE_NET_PROTOCOL_ISCSI,
                                      iscsisrc->auth) < 0)
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
                goto error;

            hostdevPriv->secinfo = secinfo;
        }
    }

    return 0;

 error:
    qemuDomainSecretInfoFree(&secinfo);
    return -1;
}


1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
/* qemuDomainSecretDestroy:
 * @vm: Domain object
 *
 * Once completed with the generation of the command line it is
 * expect to remove the secrets
 */
void
qemuDomainSecretDestroy(virDomainObjPtr vm)
{
    size_t i;

    for (i = 0; i < vm->def->ndisks; i++)
        qemuDomainSecretDiskDestroy(vm->def->disks[i]);
1111 1112 1113

    for (i = 0; i < vm->def->nhostdevs; i++)
        qemuDomainSecretHostdevDestroy(vm->def->hostdevs[i]);
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
}


/* qemuDomainSecretPrepare:
 * @conn: Pointer to connection
 * @vm: Domain object
 *
 * For any objects that may require an auth/secret setup, create a
 * qemuDomainSecretInfo and save it in the approriate place within
 * the private structures. This will be used by command line build
 * code in order to pass the secret along to qemu in order to provide
 * the necessary authentication data.
 *
 * Returns 0 on success, -1 on failure with error message set
 */
int
qemuDomainSecretPrepare(virConnectPtr conn,
                        virDomainObjPtr vm)
{
J
John Ferlan 已提交
1133
    qemuDomainObjPrivatePtr priv = vm->privateData;
1134 1135 1136
    size_t i;

    for (i = 0; i < vm->def->ndisks; i++) {
J
John Ferlan 已提交
1137
        if (qemuDomainSecretDiskPrepare(conn, priv, vm->def->disks[i]) < 0)
1138 1139 1140
            return -1;
    }

1141
    for (i = 0; i < vm->def->nhostdevs; i++) {
J
John Ferlan 已提交
1142 1143
        if (qemuDomainSecretHostdevPrepare(conn, priv,
                                           vm->def->hostdevs[i]) < 0)
1144 1145 1146
            return -1;
    }

1147 1148 1149 1150
    return 0;
}


1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
/* This is the old way of setting up per-domain directories */
static int
qemuDomainSetPrivatePathsOld(virQEMUDriverPtr driver,
                             virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    int ret = -1;

    if (!priv->libDir &&
        virAsprintf(&priv->libDir, "%s/domain-%s",
                    cfg->libDir, vm->def->name) < 0)
        goto cleanup;

    if (!priv->channelTargetDir &&
        virAsprintf(&priv->channelTargetDir, "%s/domain-%s",
                    cfg->channelTargetDir, vm->def->name) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    virObjectUnref(cfg);
    return ret;
}


int
1178 1179
qemuDomainSetPrivatePaths(virQEMUDriverPtr driver,
                          virDomainObjPtr vm)
1180
{
1181 1182
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    qemuDomainObjPrivatePtr priv = vm->privateData;
M
Martin Kletzander 已提交
1183
    char *domname = virDomainObjGetShortName(vm);
1184
    int ret = -1;
1185

M
Martin Kletzander 已提交
1186 1187 1188
    if (!domname)
        goto cleanup;

1189
    if (!priv->libDir &&
M
Martin Kletzander 已提交
1190
        virAsprintf(&priv->libDir, "%s/domain-%s", cfg->libDir, domname) < 0)
1191
        goto cleanup;
1192

1193
    if (!priv->channelTargetDir &&
M
Martin Kletzander 已提交
1194 1195
        virAsprintf(&priv->channelTargetDir, "%s/domain-%s",
                    cfg->channelTargetDir, domname) < 0)
1196
        goto cleanup;
1197

1198 1199 1200
    ret = 0;
 cleanup:
    virObjectUnref(cfg);
M
Martin Kletzander 已提交
1201
    VIR_FREE(domname);
1202
    return ret;
1203 1204 1205
}


1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
void
qemuDomainClearPrivatePaths(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    VIR_FREE(priv->libDir);
    VIR_FREE(priv->channelTargetDir);
}


1216 1217
static void *
qemuDomainObjPrivateAlloc(void)
1218 1219 1220 1221 1222 1223
{
    qemuDomainObjPrivatePtr priv;

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

1224 1225 1226
    if (qemuDomainObjInitJob(priv) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to init qemu driver mutexes"));
1227
        goto error;
1228
    }
1229

1230
    if (!(priv->devs = virChrdevAlloc()))
1231 1232
        goto error;

1233
    priv->migMaxBandwidth = QEMU_DOMAIN_MIG_BANDWIDTH_MAX;
1234

1235
    return priv;
1236

1237
 error:
1238 1239
    VIR_FREE(priv);
    return NULL;
1240 1241
}

1242 1243
static void
qemuDomainObjPrivateFree(void *data)
1244 1245 1246
{
    qemuDomainObjPrivatePtr priv = data;

1247
    virObjectUnref(priv->qemuCaps);
1248

1249
    virCgroupFree(&priv->cgroup);
1250
    virDomainPCIAddressSetFree(priv->pciaddrs);
J
Ján Tomko 已提交
1251
    virDomainCCWAddressSetFree(priv->ccwaddrs);
1252
    virDomainVirtioSerialAddrSetFree(priv->vioserialaddrs);
1253
    virDomainChrSourceDefFree(priv->monConfig);
1254
    qemuDomainObjFreeJob(priv);
1255
    VIR_FREE(priv->vcpupids);
1256
    VIR_FREE(priv->lockState);
J
Jiri Denemark 已提交
1257
    VIR_FREE(priv->origname);
1258

1259
    virStringFreeList(priv->qemuDevices);
1260
    virChrdevFree(priv->devs);
1261

1262 1263
    /* This should never be non-NULL if we get here, but just in case... */
    if (priv->mon) {
1264
        VIR_ERROR(_("Unexpected QEMU monitor still active during domain deletion"));
1265 1266
        qemuMonitorClose(priv->mon);
    }
D
Daniel P. Berrange 已提交
1267 1268 1269 1270
    if (priv->agent) {
        VIR_ERROR(_("Unexpected QEMU agent still active during domain deletion"));
        qemuAgentClose(priv->agent);
    }
1271
    VIR_FREE(priv->cleanupCallbacks);
1272
    virBitmapFree(priv->autoNodeset);
1273
    virBitmapFree(priv->autoCpuset);
1274 1275 1276 1277

    VIR_FREE(priv->libDir);
    VIR_FREE(priv->channelTargetDir);

1278 1279 1280 1281
    VIR_FREE(priv);
}


1282
static int
1283 1284
qemuDomainObjPrivateXMLFormat(virBufferPtr buf,
                              virDomainObjPtr vm)
1285
{
1286
    qemuDomainObjPrivatePtr priv = vm->privateData;
1287
    const char *monitorpath;
1288
    qemuDomainJob job;
1289 1290 1291

    /* priv->monitor_chr is set only for qemu */
    if (priv->monConfig) {
1292
        switch (priv->monConfig->type) {
1293
        case VIR_DOMAIN_CHR_TYPE_UNIX:
1294
            monitorpath = priv->monConfig->data.nix.path;
1295 1296 1297
            break;
        default:
        case VIR_DOMAIN_CHR_TYPE_PTY:
1298
            monitorpath = priv->monConfig->data.file.path;
1299 1300 1301
            break;
        }

1302
        virBufferEscapeString(buf, "<monitor path='%s'", monitorpath);
1303 1304
        if (priv->monJSON)
            virBufferAddLit(buf, " json='1'");
1305
        virBufferAsprintf(buf, " type='%s'/>\n",
1306
                          virDomainChrTypeToString(priv->monConfig->type));
1307 1308 1309 1310
    }


    if (priv->nvcpupids) {
1311
        size_t i;
1312 1313
        virBufferAddLit(buf, "<vcpus>\n");
        virBufferAdjustIndent(buf, 2);
1314
        for (i = 0; i < priv->nvcpupids; i++)
1315 1316 1317
            virBufferAsprintf(buf, "<vcpu pid='%d'/>\n", priv->vcpupids[i]);
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</vcpus>\n");
1318 1319
    }

1320
    if (priv->qemuCaps) {
1321
        size_t i;
1322 1323
        virBufferAddLit(buf, "<qemuCaps>\n");
        virBufferAdjustIndent(buf, 2);
1324
        for (i = 0; i < QEMU_CAPS_LAST; i++) {
1325
            if (virQEMUCapsGet(priv->qemuCaps, i)) {
1326
                virBufferAsprintf(buf, "<flag name='%s'/>\n",
1327
                                  virQEMUCapsTypeToString(i));
1328 1329
            }
        }
1330 1331
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</qemuCaps>\n");
1332 1333
    }

1334
    if (priv->lockState)
1335
        virBufferAsprintf(buf, "<lockstate>%s</lockstate>\n", priv->lockState);
1336

1337 1338 1339 1340
    job = priv->job.active;
    if (!qemuDomainTrackJob(job))
        priv->job.active = QEMU_JOB_NONE;

1341
    if (priv->job.active || priv->job.asyncJob) {
1342
        virBufferAsprintf(buf, "<job type='%s' async='%s'",
1343 1344
                          qemuDomainJobTypeToString(priv->job.active),
                          qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
J
Jiri Denemark 已提交
1345 1346 1347 1348 1349
        if (priv->job.phase) {
            virBufferAsprintf(buf, " phase='%s'",
                              qemuDomainAsyncJobPhaseToString(
                                    priv->job.asyncJob, priv->job.phase));
        }
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
        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");
        }
1371
    }
1372
    priv->job.active = job;
1373

1374
    if (priv->fakeReboot)
1375
        virBufferAddLit(buf, "<fakereboot/>\n");
1376

1377 1378
    if (priv->qemuDevices && *priv->qemuDevices) {
        char **tmp = priv->qemuDevices;
1379 1380
        virBufferAddLit(buf, "<devices>\n");
        virBufferAdjustIndent(buf, 2);
1381
        while (*tmp) {
1382
            virBufferAsprintf(buf, "<device alias='%s'/>\n", *tmp);
1383 1384
            tmp++;
        }
1385 1386
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</devices>\n");
1387 1388
    }

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    if (priv->autoNodeset) {
        char *nodeset = virBitmapFormat(priv->autoNodeset);

        if (!nodeset)
            return -1;

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

1399 1400 1401 1402 1403
    /* Various per-domain paths */
    virBufferEscapeString(buf, "<libDir path='%s'/>\n", priv->libDir);
    virBufferEscapeString(buf, "<channelTargetDir path='%s'/>\n",
                          priv->channelTargetDir);

1404 1405 1406
    return 0;
}

1407
static int
1408
qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt,
1409
                             virDomainObjPtr vm,
1410
                             virDomainDefParserConfigPtr config)
1411
{
1412
    qemuDomainObjPrivatePtr priv = vm->privateData;
1413
    virQEMUDriverPtr driver = config->priv;
1414
    char *monitorpath;
1415
    char *tmp = NULL;
1416 1417
    int n;
    size_t i;
1418
    xmlNodePtr *nodes = NULL;
1419
    virQEMUCapsPtr qemuCaps = NULL;
1420
    virCapsPtr caps = NULL;
1421

1422
    if (VIR_ALLOC(priv->monConfig) < 0)
1423 1424 1425 1426
        goto error;

    if (!(monitorpath =
          virXPathString("string(./monitor[1]/@path)", ctxt))) {
1427 1428
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no monitor path"));
1429 1430 1431 1432 1433
        goto error;
    }

    tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
    if (tmp)
1434
        priv->monConfig->type = virDomainChrTypeFromString(tmp);
1435
    else
1436
        priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
1437 1438
    VIR_FREE(tmp);

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

1442
    switch (priv->monConfig->type) {
1443
    case VIR_DOMAIN_CHR_TYPE_PTY:
1444
        priv->monConfig->data.file.path = monitorpath;
1445 1446
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
1447
        priv->monConfig->data.nix.path = monitorpath;
1448 1449 1450
        break;
    default:
        VIR_FREE(monitorpath);
1451 1452 1453
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported monitor type '%s'"),
                       virDomainChrTypeToString(priv->monConfig->type));
1454 1455 1456 1457 1458 1459 1460 1461
        goto error;
    }

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

1465
        for (i = 0; i < n; i++) {
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
            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);
    }
1478

1479
    if ((n = virXPathNodeSet("./qemuCaps/flag", ctxt, &nodes)) < 0) {
1480 1481
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to parse qemu capabilities flags"));
1482 1483 1484
        goto error;
    }
    if (n > 0) {
1485
        if (!(qemuCaps = virQEMUCapsNew()))
1486 1487
            goto error;

1488
        for (i = 0; i < n; i++) {
1489 1490
            char *str = virXMLPropString(nodes[i], "name");
            if (str) {
1491
                int flag = virQEMUCapsTypeFromString(str);
1492
                if (flag < 0) {
1493 1494
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unknown qemu capabilities flag %s"), str);
1495
                    VIR_FREE(str);
1496 1497
                    goto error;
                }
1498
                VIR_FREE(str);
1499
                virQEMUCapsSet(qemuCaps, flag);
1500 1501 1502
            }
        }

1503
        priv->qemuCaps = qemuCaps;
1504
        qemuCaps = NULL;
1505 1506 1507
    }
    VIR_FREE(nodes);

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

1510 1511 1512 1513
    if ((tmp = virXPathString("string(./job[1]/@type)", ctxt))) {
        int type;

        if ((type = qemuDomainJobTypeFromString(tmp)) < 0) {
1514 1515
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown job type %s"), tmp);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
            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) {
1527 1528
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown async job type %s"), tmp);
1529 1530 1531 1532 1533
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
        priv->job.asyncJob = async;
J
Jiri Denemark 已提交
1534 1535 1536 1537

        if ((tmp = virXPathString("string(./job[1]/@phase)", ctxt))) {
            priv->job.phase = qemuDomainAsyncJobPhaseFromString(async, tmp);
            if (priv->job.phase < 0) {
1538 1539
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unknown job phase %s"), tmp);
J
Jiri Denemark 已提交
1540 1541 1542 1543 1544
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        }
1545 1546
    }

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    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);

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

1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    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);

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    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);
    VIR_FREE(tmp);

1608 1609 1610 1611 1612 1613 1614 1615 1616
    if ((tmp = virXPathString("string(./libDir/@path)", ctxt)))
        priv->libDir = tmp;
    if ((tmp = virXPathString("string(./channelTargetDir/@path)", ctxt)))
        priv->channelTargetDir = tmp;
    tmp = NULL;

    if (qemuDomainSetPrivatePathsOld(driver, vm) < 0)
        goto error;

1617 1618
    return 0;

1619
 error:
1620
    virDomainChrSourceDefFree(priv->monConfig);
1621 1622
    priv->monConfig = NULL;
    VIR_FREE(nodes);
1623
    VIR_FREE(tmp);
1624 1625
    virStringFreeList(priv->qemuDevices);
    priv->qemuDevices = NULL;
1626
    virObjectUnref(qemuCaps);
1627
    virObjectUnref(caps);
1628 1629 1630 1631
    return -1;
}


1632 1633 1634
virDomainXMLPrivateDataCallbacks virQEMUDriverPrivateDataCallbacks = {
    .alloc = qemuDomainObjPrivateAlloc,
    .free = qemuDomainObjPrivateFree,
1635
    .diskNew = qemuDomainDiskPrivateNew,
1636
    .hostdevNew = qemuDomainHostdevPrivateNew,
1637 1638 1639 1640 1641
    .parse = qemuDomainObjPrivateXMLParse,
    .format = qemuDomainObjPrivateXMLFormat,
};


1642 1643 1644 1645 1646
static void
qemuDomainDefNamespaceFree(void *nsdata)
{
    qemuDomainCmdlineDefPtr cmd = nsdata;

1647
    qemuDomainCmdlineDefFree(cmd);
1648 1649 1650
}

static int
P
Philipp Hahn 已提交
1651 1652
qemuDomainDefNamespaceParse(xmlDocPtr xml ATTRIBUTE_UNUSED,
                            xmlNodePtr root ATTRIBUTE_UNUSED,
1653 1654 1655 1656
                            xmlXPathContextPtr ctxt,
                            void **data)
{
    qemuDomainCmdlineDefPtr cmd = NULL;
P
Philipp Hahn 已提交
1657
    bool uses_qemu_ns = false;
1658
    xmlNodePtr *nodes = NULL;
1659 1660
    int n;
    size_t i;
1661

P
Philipp Hahn 已提交
1662
    if (xmlXPathRegisterNs(ctxt, BAD_CAST "qemu", BAD_CAST QEMU_NAMESPACE_HREF) < 0) {
1663 1664 1665
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to register xml namespace '%s'"),
                       QEMU_NAMESPACE_HREF);
1666 1667 1668
        return -1;
    }

1669
    if (VIR_ALLOC(cmd) < 0)
1670 1671 1672 1673 1674 1675
        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 已提交
1676
    uses_qemu_ns |= n > 0;
1677 1678

    if (n && VIR_ALLOC_N(cmd->args, n) < 0)
1679
        goto error;
1680 1681 1682 1683

    for (i = 0; i < n; i++) {
        cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
        if (cmd->args[cmd->num_args] == NULL) {
1684 1685
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu command-line argument specified"));
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
            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 已提交
1697
    uses_qemu_ns |= n > 0;
1698 1699

    if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
1700
        goto error;
1701 1702

    if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
1703
        goto error;
1704 1705 1706 1707 1708 1709

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

        tmp = virXMLPropString(nodes[i], "name");
        if (tmp == NULL) {
1710 1711
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("No qemu environment name specified"));
1712 1713 1714
            goto error;
        }
        if (tmp[0] == '\0') {
1715 1716
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Empty qemu environment name specified"));
1717 1718 1719
            goto error;
        }
        if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
1720 1721
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must begin with a letter or underscore"));
1722 1723 1724
            goto error;
        }
        if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
1725 1726
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
            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 已提交
1739 1740 1741 1742
    if (uses_qemu_ns)
        *data = cmd;
    else
        VIR_FREE(cmd);
1743 1744 1745

    return 0;

1746
 error:
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
    VIR_FREE(nodes);
    qemuDomainDefNamespaceFree(cmd);
    return -1;
}

static int
qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
                                void *nsdata)
{
    qemuDomainCmdlineDefPtr cmd = nsdata;
1757
    size_t i;
1758 1759 1760 1761

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

1762 1763 1764
    virBufferAddLit(buf, "<qemu:commandline>\n");
    virBufferAdjustIndent(buf, 2);

1765
    for (i = 0; i < cmd->num_args; i++)
1766
        virBufferEscapeString(buf, "<qemu:arg value='%s'/>\n",
1767 1768
                              cmd->args[i]);
    for (i = 0; i < cmd->num_env; i++) {
1769
        virBufferAsprintf(buf, "<qemu:env name='%s'", cmd->env_name[i]);
1770 1771 1772 1773 1774
        if (cmd->env_value[i])
            virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
        virBufferAddLit(buf, "/>\n");
    }

1775 1776
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</qemu:commandline>\n");
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    return 0;
}

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


1787 1788 1789 1790 1791 1792
virDomainXMLNamespace virQEMUDriverDomainXMLNamespace = {
    .parse = qemuDomainDefNamespaceParse,
    .free = qemuDomainDefNamespaceFree,
    .format = qemuDomainDefNamespaceFormatXML,
    .href = qemuDomainDefNamespaceHref,
};
1793

1794

P
Pavel Hrdina 已提交
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
static int
qemuDomainDefAddImplicitInputDevice(virDomainDef *def)
{
    if (ARCH_IS_X86(def->os.arch)) {
        if (virDomainDefMaybeAddInput(def,
                                      VIR_DOMAIN_INPUT_TYPE_MOUSE,
                                      VIR_DOMAIN_INPUT_BUS_PS2) < 0)
            return -1;

        if (virDomainDefMaybeAddInput(def,
                                      VIR_DOMAIN_INPUT_TYPE_KBD,
                                      VIR_DOMAIN_INPUT_BUS_PS2) < 0)
            return -1;
    }

    return 0;
}


1814
static int
1815 1816
qemuDomainDefAddDefaultDevices(virDomainDefPtr def,
                               virQEMUCapsPtr qemuCaps)
1817
{
1818
    bool addDefaultUSB = true;
1819
    int usbModel = -1; /* "default for machinetype" */
1820
    int pciRoot;       /* index within def->controllers */
1821
    bool addImplicitSATA = false;
1822
    bool addPCIRoot = false;
L
Laine Stump 已提交
1823
    bool addPCIeRoot = false;
1824
    bool addDefaultMemballoon = true;
1825 1826
    bool addDefaultUSBKBD = false;
    bool addDefaultUSBMouse = false;
1827
    bool addPanicDevice = false;
1828
    int ret = -1;
1829

P
Pavel Hrdina 已提交
1830 1831 1832 1833
    /* add implicit input devices */
    if (qemuDomainDefAddImplicitInputDevice(def) < 0)
        goto cleanup;

1834 1835 1836 1837
    /* Add implicit PCI root controller if the machine has one */
    switch (def->os.arch) {
    case VIR_ARCH_I686:
    case VIR_ARCH_X86_64:
L
Laine Stump 已提交
1838
        if (STREQ(def->os.machine, "isapc")) {
1839
            addDefaultUSB = false;
1840
            break;
1841
        }
1842
        if (qemuDomainMachineIsQ35(def)) {
1843 1844
            addPCIeRoot = true;
            addImplicitSATA = true;
1845 1846 1847 1848 1849 1850 1851 1852

            /* add a USB2 controller set, but only if the
             * ich9-usb-ehci1 device is supported
             */
            if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_ICH9_USB_EHCI1))
                usbModel = VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1;
            else
                addDefaultUSB = false;
1853
            break;
L
Laine Stump 已提交
1854
        }
1855 1856
        if (qemuDomainMachineIsI440FX(def))
            addPCIRoot = true;
1857 1858
        break;

1859
    case VIR_ARCH_ARMV7L:
1860
    case VIR_ARCH_AARCH64:
1861 1862
        addDefaultUSB = false;
        addDefaultMemballoon = false;
J
Ján Tomko 已提交
1863
        if (qemuDomainMachineIsVirt(def))
1864 1865
            addPCIeRoot = virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_GPEX);
        break;
1866

1867
    case VIR_ARCH_PPC64:
1868
    case VIR_ARCH_PPC64LE:
1869 1870 1871
        addPCIRoot = true;
        addDefaultUSBKBD = true;
        addDefaultUSBMouse = true;
1872 1873 1874 1875 1876
        /* 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;
1877 1878
        break;

1879 1880 1881 1882 1883 1884 1885
    case VIR_ARCH_ALPHA:
    case VIR_ARCH_PPC:
    case VIR_ARCH_PPCEMB:
    case VIR_ARCH_SH4:
    case VIR_ARCH_SH4EB:
        addPCIRoot = true;
        break;
1886

1887 1888 1889
    case VIR_ARCH_S390:
    case VIR_ARCH_S390X:
        addDefaultUSB = false;
1890
        addPanicDevice = true;
1891
        break;
1892 1893 1894 1895 1896 1897

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

1898 1899 1900 1901
    default:
        break;
    }

1902
    if (addDefaultUSB &&
1903 1904
        virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_USB, 0) < 0 &&
        virDomainDefAddUSBController(def, 0, usbModel) < 0)
1905
        goto cleanup;
1906

1907 1908 1909
    if (addImplicitSATA &&
        virDomainDefMaybeAddController(
            def, VIR_DOMAIN_CONTROLLER_TYPE_SATA, 0, -1) < 0)
1910
        goto cleanup;
1911

1912 1913
    pciRoot = virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0);

1914 1915 1916
    /* NB: any machine that sets addPCIRoot to true must also return
     * true from the function qemuDomainSupportsPCI().
     */
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
    if (addPCIRoot) {
        if (pciRoot >= 0) {
            if (def->controllers[pciRoot]->model != VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("The PCI controller with index='0' must be "
                                 "model='pci-root' for this machine type, "
                                 "but model='%s' was found instead"),
                               virDomainControllerModelPCITypeToString(def->controllers[pciRoot]->model));
                goto cleanup;
            }
        } else if (!virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
                                              VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT)) {
            goto cleanup;
        }
    }
1932

1933 1934 1935
    /* 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
1936 1937 1938
     *
     * NB: any machine that sets addPCIeRoot to true must also return
     * true from the function qemuDomainSupportsPCI().
1939 1940
     */
    if (addPCIeRoot) {
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
        if (pciRoot >= 0) {
            if (def->controllers[pciRoot]->model != VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("The PCI controller with index='0' must be "
                                 "model='pcie-root' for this machine type, "
                                 "but model='%s' was found instead"),
                               virDomainControllerModelPCITypeToString(def->controllers[pciRoot]->model));
                goto cleanup;
            }
        } else if (!virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
                                             VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)) {
            goto cleanup;
        }
1954 1955 1956 1957 1958 1959 1960 1961
        /* add a dmi-to-pci-bridge and a pci-bridge if there are no pci controllers
         * other than the pcie-root. This is so that there will be hot-pluggable
         * PCI slots available
         */
        if (virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 1) < 0 &&
            !virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 1,
                                      VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE))
            goto cleanup;
1962
    }
1963

1964
    if (addDefaultMemballoon && !def->memballoon) {
1965 1966
        virDomainMemballoonDefPtr memballoon;
        if (VIR_ALLOC(memballoon) < 0)
1967
            goto cleanup;
1968 1969 1970 1971 1972

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

1973 1974 1975 1976 1977
    if (addDefaultUSBKBD &&
        def->ngraphics > 0 &&
        virDomainDefMaybeAddInput(def,
                                  VIR_DOMAIN_INPUT_TYPE_KBD,
                                  VIR_DOMAIN_INPUT_BUS_USB) < 0)
1978
        goto cleanup;
1979 1980 1981 1982 1983 1984

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

D
Dmitry Andreev 已提交
1987 1988 1989 1990
    if (addPanicDevice) {
        size_t j;
        for (j = 0; j < def->npanics; j++) {
            if (def->panics[j]->model == VIR_DOMAIN_PANIC_MODEL_DEFAULT ||
1991 1992 1993 1994
                (ARCH_IS_PPC64(def->os.arch) &&
                     def->panics[j]->model == VIR_DOMAIN_PANIC_MODEL_PSERIES) ||
                (ARCH_IS_S390(def->os.arch) &&
                     def->panics[j]->model == VIR_DOMAIN_PANIC_MODEL_S390))
D
Dmitry Andreev 已提交
1995 1996
                break;
        }
1997

D
Dmitry Andreev 已提交
1998 1999 2000 2001 2002 2003 2004 2005 2006
        if (j == def->npanics) {
            virDomainPanicDefPtr panic;
            if (VIR_ALLOC(panic) < 0 ||
                VIR_APPEND_ELEMENT_COPY(def->panics,
                                        def->npanics, panic) < 0) {
                VIR_FREE(panic);
                goto cleanup;
            }
        }
2007 2008
    }

2009 2010 2011 2012 2013 2014
    ret = 0;
 cleanup:
    return ret;
}


A
Andrea Bolognani 已提交
2015 2016 2017
/**
 * qemuDomainDefEnableDefaultFeatures:
 * @def: domain definition
2018
 * @qemuCaps: QEMU capabilities
A
Andrea Bolognani 已提交
2019 2020 2021 2022 2023
 *
 * Make sure that features that should be enabled by default are actually
 * enabled and configure default values related to those features.
 */
static void
2024 2025
qemuDomainDefEnableDefaultFeatures(virDomainDefPtr def,
                                   virQEMUCapsPtr qemuCaps)
A
Andrea Bolognani 已提交
2026
{
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
    virGICVersion version;

    /* The virt machine type always uses GIC: if the relevant element
     * was not included in the domain XML, we need to choose a suitable
     * GIC version ourselves */
    if (def->features[VIR_DOMAIN_FEATURE_GIC] == VIR_TRISTATE_SWITCH_ABSENT &&
        (def->os.arch == VIR_ARCH_ARMV7L || def->os.arch == VIR_ARCH_AARCH64) &&
        qemuDomainMachineIsVirt(def)) {

        VIR_DEBUG("Looking for usable GIC version in domain capabilities");
        for (version = VIR_GIC_VERSION_LAST - 1;
             version > VIR_GIC_VERSION_NONE;
             version--) {
            if (virQEMUCapsSupportsGICVersion(qemuCaps,
                                              def->virtType,
                                              version)) {
                VIR_DEBUG("Using GIC version %s",
                          virGICVersionTypeToString(version));
                def->gic_version = version;
                break;
            }
2048 2049
        }

2050 2051 2052
        /* Even if we haven't found a usable GIC version in the domain
         * capabilities, we still want to enable this */
        def->features[VIR_DOMAIN_FEATURE_GIC] = VIR_TRISTATE_SWITCH_ON;
2053 2054
    }

2055
    /* Use the default GIC version if no version was specified */
A
Andrea Bolognani 已提交
2056 2057
    if (def->features[VIR_DOMAIN_FEATURE_GIC] == VIR_TRISTATE_SWITCH_ON &&
        def->gic_version == VIR_GIC_VERSION_NONE)
2058
        def->gic_version = VIR_GIC_VERSION_DEFAULT;
A
Andrea Bolognani 已提交
2059 2060 2061
}


2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
static int
qemuCanonicalizeMachine(virDomainDefPtr def, virQEMUCapsPtr qemuCaps)
{
    const char *canon;

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

    if (STRNEQ(canon, def->os.machine)) {
        char *tmp;
        if (VIR_STRDUP(tmp, canon) < 0)
            return -1;
        VIR_FREE(def->os.machine);
        def->os.machine = tmp;
    }

    return 0;
}


2082
static int
2083 2084 2085 2086 2087
qemuDomainRecheckInternalPaths(virDomainDefPtr def,
                               virQEMUDriverConfigPtr cfg,
                               unsigned int flags)
{
    size_t i = 0;
2088
    size_t j = 0;
2089 2090 2091 2092

    for (i = 0; i < def->ngraphics; ++i) {
        virDomainGraphicsDefPtr graphics = def->graphics[i];

2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
        for (j = 0; j < graphics->nListens; ++j) {
            virDomainGraphicsListenDefPtr glisten =  &graphics->listens[j];

            /* This will happen only if we parse XML from old libvirts where
             * unix socket was available only for VNC graphics.  In this
             * particular case we should follow the behavior and if we remove
             * the auto-generated socket base on config option from qemu.conf
             * we need to change the listen type to address. */
            if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
                glisten->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_SOCKET &&
                glisten->socket &&
                STRPREFIX(glisten->socket, cfg->libDir)) {
                if (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) {
                    VIR_FREE(glisten->socket);
                    glisten->type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS;
                } else {
                    glisten->fromConfig = true;
                }
2111
            }
2112 2113
        }
    }
2114 2115

    return 0;
2116 2117 2118
}


2119 2120 2121
static int
qemuDomainDefPostParse(virDomainDefPtr def,
                       virCapsPtr caps,
2122
                       unsigned int parseFlags,
2123 2124 2125
                       void *opaque)
{
    virQEMUDriverPtr driver = opaque;
2126
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2127 2128 2129 2130 2131 2132 2133 2134 2135
    virQEMUCapsPtr qemuCaps = NULL;
    int ret = -1;

    if (def->os.bootloader || def->os.bootloaderArgs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("bootloader is not supported by QEMU"));
        return ret;
    }

2136 2137 2138 2139 2140 2141
    if (!def->os.machine) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing machine type"));
        return ret;
    }

2142 2143 2144 2145 2146 2147 2148 2149 2150
    if (def->os.loader &&
        def->os.loader->type == VIR_DOMAIN_LOADER_TYPE_PFLASH &&
        def->os.loader->readonly == VIR_TRISTATE_SWITCH_ON &&
        !def->os.loader->nvram) {
        if (virAsprintf(&def->os.loader->nvram, "%s/%s_VARS.fd",
                        cfg->nvramDir, def->name) < 0)
            goto cleanup;
    }

2151 2152 2153 2154 2155
    /* check for emulator and create a default one if needed */
    if (!def->emulator &&
        !(def->emulator = virDomainDefGetDefaultEmulator(def, caps)))
        return ret;

2156 2157 2158
    if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache,
                                            def->emulator)))
        goto cleanup;
2159 2160 2161 2162

    if (qemuDomainDefAddDefaultDevices(def, qemuCaps) < 0)
        goto cleanup;

2163 2164 2165
    if (qemuCanonicalizeMachine(def, qemuCaps) < 0)
        goto cleanup;

2166
    qemuDomainDefEnableDefaultFeatures(def, qemuCaps);
A
Andrea Bolognani 已提交
2167

2168 2169
    if (qemuDomainRecheckInternalPaths(def, cfg, parseFlags) < 0)
        goto cleanup;
2170

2171 2172 2173
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
        goto cleanup;

2174 2175 2176
    ret = 0;
 cleanup:
    virObjectUnref(qemuCaps);
2177
    virObjectUnref(cfg);
2178
    return ret;
2179 2180
}

2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196

static int
qemuDomainDefValidate(const virDomainDef *def,
                      virCapsPtr caps ATTRIBUTE_UNUSED,
                      void *opaque ATTRIBUTE_UNUSED)
{
    if (def->mem.min_guarantee) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Parameter 'min_guarantee' not supported by QEMU."));
        return -1;
    }

    return 0;
}


2197
static const char *
2198 2199
qemuDomainDefaultNetModel(const virDomainDef *def,
                          virQEMUCapsPtr qemuCaps)
2200
{
2201
    if (ARCH_IS_S390(def->os.arch))
2202 2203
        return "virtio";

2204 2205
    if (def->os.arch == VIR_ARCH_ARMV7L ||
        def->os.arch == VIR_ARCH_AARCH64) {
2206 2207 2208
        if (STREQ(def->os.machine, "versatilepb"))
            return "smc91c111";

J
Ján Tomko 已提交
2209
        if (qemuDomainMachineIsVirt(def))
2210 2211
            return "virtio";

2212 2213 2214 2215 2216
        /* Incomplete. vexpress (and a few others) use this, but not all
         * arm boards */
        return "lan9118";
    }

2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
    /* 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 */
2229 2230
    return "rtl8139";
}
2231

2232 2233
static int
qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
2234
                             const virDomainDef *def,
2235
                             virCapsPtr caps ATTRIBUTE_UNUSED,
2236
                             unsigned int parseFlags,
2237
                             void *opaque)
2238
{
2239
    virQEMUDriverPtr driver = opaque;
2240
    virQEMUCapsPtr qemuCaps = NULL;
2241
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2242
    int ret = -1;
2243

P
Pavel Fedin 已提交
2244
    qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator);
2245

2246
    if (dev->type == VIR_DOMAIN_DEVICE_NET &&
2247 2248
        dev->data.net->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
        !dev->data.net->model) {
2249
        if (VIR_STRDUP(dev->data.net->model,
2250
                       qemuDomainDefaultNetModel(def, qemuCaps)) < 0)
2251
            goto cleanup;
2252
    }
2253

2254 2255 2256 2257
    /* set default disk types and drivers */
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        virDomainDiskDefPtr disk = dev->data.disk;

2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
        /* assign default storage format and driver according to config */
        if (cfg->allowDiskFormatProbing) {
            /* default disk format for drives */
            if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
                (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                 virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
                virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_AUTO);

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

            /* default disk format for drives */
            if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
                (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE ||
                 virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_BLOCK))
                virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);

            /* default disk format for mirrored drive */
            if (disk->mirror &&
                disk->mirror->format == VIR_STORAGE_FILE_NONE)
                disk->mirror->format = VIR_STORAGE_FILE_RAW;
2286 2287 2288
        }
    }

2289 2290 2291 2292
    /* 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 &&
2293
        ARCH_IS_S390(def->os.arch))
2294 2295
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO;

2296 2297 2298 2299 2300
    /* 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 &&
2301
        ARCH_IS_S390(def->os.arch))
2302 2303
        dev->data.controller->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE;

2304 2305 2306 2307 2308 2309 2310
    /* 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;

2311 2312 2313
    /* clear auto generated unix socket path for inactive definitions */
    if ((parseFlags & VIR_DOMAIN_DEF_PARSE_INACTIVE) &&
        dev->type == VIR_DOMAIN_DEVICE_CHR &&
2314 2315 2316
        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 &&
2317 2318 2319 2320 2321 2322
        dev->data.chr->source.data.nix.path &&
        STRPREFIX(dev->data.chr->source.data.nix.path, cfg->channelTargetDir)) {
        /*
         * If the address is generated by us (starts with our
         * channel dir), we should not keep it in the persistent
         * XML.  If libvirt is the one who generated it, users
2323
         * shouldn't care about that.  If they do, they are
2324 2325 2326
         * supposed to set it themselves.
         */
        VIR_FREE(dev->data.chr->source.data.nix.path);
2327 2328
    }

2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
    /* 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;
    }

2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
    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 {
2354
            dev->data.video->vgamem = QEMU_QXL_VGAMEM_DEFAULT;
2355 2356 2357
        }
    }

2358 2359 2360 2361 2362
    if (dev->type == VIR_DOMAIN_DEVICE_PANIC &&
        dev->data.panic->model == VIR_DOMAIN_PANIC_MODEL_DEFAULT) {
        if (ARCH_IS_PPC64(def->os.arch) &&
            STRPREFIX(def->os.machine, "pseries"))
            dev->data.panic->model = VIR_DOMAIN_PANIC_MODEL_PSERIES;
2363 2364
        else if (ARCH_IS_S390(def->os.arch))
            dev->data.panic->model = VIR_DOMAIN_PANIC_MODEL_S390;
2365 2366 2367 2368
        else
            dev->data.panic->model = VIR_DOMAIN_PANIC_MODEL_ISA;
    }

2369 2370 2371 2372

    if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
        virDomainControllerDefPtr cont = dev->data.controller;

2373 2374 2375
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
            if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS &&
                !qemuDomainMachineIsI440FX(def)) {
2376 2377 2378 2379 2380
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("pci-expander-bus controllers are only supported "
                                 "on 440fx-based machinetypes"));
                goto cleanup;
            }
2381 2382 2383 2384 2385 2386 2387
            if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS &&
                !qemuDomainMachineIsQ35(def)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("pcie-expander-bus controllers are only supported "
                                 "on q35-based machinetypes"));
                goto cleanup;
            }
2388 2389 2390 2391 2392 2393

            /* if a PCI expander bus has a NUMA node set, make sure
             * that NUMA node is configured in the guest <cpu><numa>
             * array. NUMA cell id's in this array are numbered
             * from 0 .. size-1.
             */
2394 2395 2396
            if ((cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS ||
                 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS) &&
                (int) virDomainNumaGetNodeCount(def->numa)
2397 2398
                <= cont->opts.pciopts.numaNode) {
                virReportError(VIR_ERR_XML_ERROR,
2399
                               _("%s with index %d is "
2400 2401 2402
                                 "configured for a NUMA node (%d) "
                                 "not present in the domain's "
                                 "<cpu><numa> array (%zu)"),
2403
                               virDomainControllerModelPCITypeToString(cont->model),
2404 2405 2406 2407 2408 2409 2410
                               cont->idx, cont->opts.pciopts.numaNode,
                               virDomainNumaGetNodeCount(def->numa));
                goto cleanup;
            }
        }
    }

2411 2412
    ret = 0;

2413
 cleanup:
2414
    virObjectUnref(qemuCaps);
2415 2416
    virObjectUnref(cfg);
    return ret;
2417 2418 2419
}


2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
static int
qemuDomainDefAssignAddresses(virDomainDef *def,
                             virCapsPtr caps ATTRIBUTE_UNUSED,
                             unsigned int parseFlags ATTRIBUTE_UNUSED,
                             void *opaque)
{
    virQEMUDriverPtr driver = opaque;
    virQEMUCapsPtr qemuCaps = NULL;
    int ret = -1;

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

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

    ret = 0;
 cleanup:
    virObjectUnref(qemuCaps);
    return ret;
}


2444 2445
virDomainDefParserConfig virQEMUDriverDomainDefParserConfig = {
    .devicesPostParseCallback = qemuDomainDeviceDefPostParse,
2446
    .domainPostParseCallback = qemuDomainDefPostParse,
2447
    .assignAddressesCallback = qemuDomainDefAssignAddresses,
2448
    .domainValidateCallback = qemuDomainDefValidate,
2449 2450
    .features = VIR_DOMAIN_DEF_FEATURE_MEMORY_HOTPLUG |
                VIR_DOMAIN_DEF_FEATURE_OFFLINE_VCPUPIN
2451 2452 2453
};


2454
static void
2455
qemuDomainObjSaveJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
2456
{
2457 2458 2459
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

    if (virDomainObjIsActive(obj)) {
2460
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, obj, driver->caps) < 0)
2461
            VIR_WARN("Failed to save status on vm %s", obj->def->name);
2462
    }
2463

2464
    virObjectUnref(cfg);
2465 2466
}

J
Jiri Denemark 已提交
2467
void
2468
qemuDomainObjSetJobPhase(virQEMUDriverPtr driver,
J
Jiri Denemark 已提交
2469 2470 2471 2472
                         virDomainObjPtr obj,
                         int phase)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
2473
    unsigned long long me = virThreadSelfID();
J
Jiri Denemark 已提交
2474 2475 2476 2477

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

2478 2479 2480 2481 2482
    VIR_DEBUG("Setting '%s' phase to '%s'",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              qemuDomainAsyncJobPhaseToString(priv->job.asyncJob, phase));

    if (priv->job.asyncOwner && me != priv->job.asyncOwner) {
2483
        VIR_WARN("'%s' async job is owned by thread %llu",
2484 2485 2486 2487
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }

J
Jiri Denemark 已提交
2488
    priv->job.phase = phase;
2489
    priv->job.asyncOwner = me;
J
Jiri Denemark 已提交
2490 2491 2492
    qemuDomainObjSaveJob(driver, obj);
}

2493
void
2494 2495
qemuDomainObjSetAsyncJobMask(virDomainObjPtr obj,
                             unsigned long long allowedJobs)
2496 2497 2498
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

2499 2500 2501 2502 2503 2504 2505
    if (!priv->job.asyncJob)
        return;

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

void
2506
qemuDomainObjDiscardAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
2507 2508 2509 2510 2511 2512
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    if (priv->job.active == QEMU_JOB_ASYNC_NESTED)
        qemuDomainObjResetJob(priv);
    qemuDomainObjResetAsyncJob(priv);
2513
    qemuDomainObjSaveJob(driver, obj);
2514 2515
}

2516 2517 2518 2519 2520 2521 2522 2523 2524
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()) {
2525
        VIR_WARN("'%s' async job is owned by thread %llu",
2526 2527 2528 2529 2530 2531
                 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                 priv->job.asyncOwner);
    }
    priv->job.asyncOwner = 0;
}

2532
static bool
2533
qemuDomainNestedJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
2534 2535
{
    return !priv->job.asyncJob || (priv->job.mask & JOB_MASK(job)) != 0;
2536 2537
}

2538
bool
2539
qemuDomainJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
2540 2541 2542 2543
{
    return !priv->job.active && qemuDomainNestedJobAllowed(priv, job);
}

2544 2545 2546
/* Give up waiting for mutex after 30 seconds */
#define QEMU_JOB_WAIT_TIME (1000ull * 30)

2547
/*
2548
 * obj must be locked before calling
2549
 */
2550
static int ATTRIBUTE_NONNULL(1)
2551
qemuDomainObjBeginJobInternal(virQEMUDriverPtr driver,
2552
                              virDomainObjPtr obj,
2553 2554
                              qemuDomainJob job,
                              qemuDomainAsyncJob asyncJob)
2555 2556
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
J
Jiri Denemark 已提交
2557
    unsigned long long now;
2558
    unsigned long long then;
2559
    bool nested = job == QEMU_JOB_ASYNC_NESTED;
J
Jiri Denemark 已提交
2560
    bool async = job == QEMU_JOB_ASYNC;
2561
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2562
    const char *blocker = NULL;
J
Jiri Denemark 已提交
2563
    int ret = -1;
J
Jiri Denemark 已提交
2564 2565
    unsigned long long duration = 0;
    unsigned long long asyncDuration = 0;
J
Jiri Denemark 已提交
2566
    const char *jobStr;
2567

J
Jiri Denemark 已提交
2568 2569 2570 2571 2572 2573 2574 2575 2576
    if (async)
        jobStr = qemuDomainAsyncJobTypeToString(asyncJob);
    else
        jobStr = qemuDomainJobTypeToString(job);

    VIR_DEBUG("Starting %s: %s (vm=%p name=%s, current job=%s async=%s)",
              async ? "async job" : "job", jobStr, obj, obj->def->name,
              qemuDomainJobTypeToString(priv->job.active),
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
2577

2578 2579
    if (virTimeMillisNow(&now) < 0) {
        virObjectUnref(cfg);
2580
        return -1;
2581 2582
    }

2583
    priv->jobs_queued++;
J
Jiri Denemark 已提交
2584
    then = now + QEMU_JOB_WAIT_TIME;
2585

2586
 retry:
2587 2588
    if (cfg->maxQueuedJobs &&
        priv->jobs_queued > cfg->maxQueuedJobs) {
2589 2590 2591
        goto error;
    }

2592
    while (!nested && !qemuDomainNestedJobAllowed(priv, job)) {
2593
        VIR_DEBUG("Waiting for async job (vm=%p name=%s)", obj, obj->def->name);
2594
        if (virCondWaitUntil(&priv->job.asyncCond, &obj->parent.lock, then) < 0)
2595 2596 2597
            goto error;
    }

2598
    while (priv->job.active) {
2599
        VIR_DEBUG("Waiting for job (vm=%p name=%s)", obj, obj->def->name);
2600
        if (virCondWaitUntil(&priv->job.cond, &obj->parent.lock, then) < 0)
2601
            goto error;
2602
    }
2603 2604 2605

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

2609
    qemuDomainObjResetJob(priv);
2610

J
Jiri Denemark 已提交
2611 2612
    ignore_value(virTimeMillisNow(&now));

2613
    if (job != QEMU_JOB_ASYNC) {
2614
        VIR_DEBUG("Started job: %s (async=%s vm=%p name=%s)",
2615
                   qemuDomainJobTypeToString(job),
2616 2617
                  qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                  obj, obj->def->name);
2618
        priv->job.active = job;
2619
        priv->job.owner = virThreadSelfID();
2620
        priv->job.ownerAPI = virThreadJobGet();
J
Jiri Denemark 已提交
2621
        priv->job.started = now;
2622
    } else {
2623 2624 2625
        VIR_DEBUG("Started async job: %s (vm=%p name=%s)",
                  qemuDomainAsyncJobTypeToString(asyncJob),
                  obj, obj->def->name);
2626
        qemuDomainObjResetAsyncJob(priv);
J
Jiri Denemark 已提交
2627 2628
        if (VIR_ALLOC(priv->job.current) < 0)
            goto cleanup;
2629
        priv->job.asyncJob = asyncJob;
2630
        priv->job.asyncOwner = virThreadSelfID();
2631
        priv->job.asyncOwnerAPI = virThreadJobGet();
J
Jiri Denemark 已提交
2632
        priv->job.asyncStarted = now;
J
Jiri Denemark 已提交
2633
        priv->job.current->started = now;
2634
    }
2635

2636 2637
    if (qemuDomainTrackJob(job))
        qemuDomainObjSaveJob(driver, obj);
2638

2639
    virObjectUnref(cfg);
2640
    return 0;
2641

2642
 error:
J
Jiri Denemark 已提交
2643 2644 2645 2646 2647 2648
    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;

2649
    VIR_WARN("Cannot start job (%s, %s) for domain %s; "
J
Jiri Denemark 已提交
2650 2651
             "current job is (%s, %s) owned by (%llu %s, %llu %s) "
             "for (%llus, %llus)",
2652 2653 2654 2655 2656
             qemuDomainJobTypeToString(job),
             qemuDomainAsyncJobTypeToString(asyncJob),
             obj->def->name,
             qemuDomainJobTypeToString(priv->job.active),
             qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
2657
             priv->job.owner, NULLSTR(priv->job.ownerAPI),
J
Jiri Denemark 已提交
2658 2659
             priv->job.asyncOwner, NULLSTR(priv->job.asyncOwnerAPI),
             duration / 1000, asyncDuration / 1000);
2660 2661 2662 2663 2664

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

2666 2667
    ret = -1;
    if (errno == ETIMEDOUT) {
2668 2669 2670 2671 2672 2673 2674 2675
        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"));
        }
2676 2677 2678
        ret = -2;
    } else if (cfg->maxQueuedJobs &&
               priv->jobs_queued > cfg->maxQueuedJobs) {
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
        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"));
        }
2689 2690
        ret = -2;
    } else {
2691
        virReportSystemError(errno, "%s", _("cannot acquire job mutex"));
2692
    }
J
Jiri Denemark 已提交
2693 2694

 cleanup:
2695
    priv->jobs_queued--;
2696
    virObjectUnref(cfg);
2697
    return ret;
2698 2699 2700
}

/*
2701
 * obj must be locked before calling
2702 2703 2704 2705
 *
 * This must be called by anything that will change the VM state
 * in any way, or anything that will use the QEMU monitor.
 *
2706
 * Successful calls must be followed by EndJob eventually
2707
 */
2708
int qemuDomainObjBeginJob(virQEMUDriverPtr driver,
2709
                          virDomainObjPtr obj,
2710
                          qemuDomainJob job)
2711
{
2712 2713 2714 2715 2716
    if (qemuDomainObjBeginJobInternal(driver, obj, job,
                                      QEMU_ASYNC_JOB_NONE) < 0)
        return -1;
    else
        return 0;
2717 2718
}

2719
int qemuDomainObjBeginAsyncJob(virQEMUDriverPtr driver,
2720
                               virDomainObjPtr obj,
2721
                               qemuDomainAsyncJob asyncJob)
2722
{
2723 2724 2725 2726 2727
    if (qemuDomainObjBeginJobInternal(driver, obj, QEMU_JOB_ASYNC,
                                      asyncJob) < 0)
        return -1;
    else
        return 0;
2728 2729
}

2730
int
2731 2732
qemuDomainObjBeginNestedJob(virQEMUDriverPtr driver,
                            virDomainObjPtr obj,
2733
                            qemuDomainAsyncJob asyncJob)
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
{
    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()) {
2744
        VIR_WARN("This thread doesn't seem to be the async job owner: %llu",
2745 2746 2747 2748 2749 2750 2751 2752
                 priv->job.asyncOwner);
    }

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

2753

2754
/*
2755
 * obj must be locked and have a reference before calling
2756 2757 2758 2759
 *
 * To be called after completing the work associated with the
 * earlier qemuDomainBeginJob() call
 */
2760 2761
void
qemuDomainObjEndJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
2762 2763
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
2764
    qemuDomainJob job = priv->job.active;
2765

2766 2767
    priv->jobs_queued--;

2768
    VIR_DEBUG("Stopping job: %s (async=%s vm=%p name=%s)",
2769
              qemuDomainJobTypeToString(job),
2770 2771
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
2772

2773
    qemuDomainObjResetJob(priv);
2774 2775
    if (qemuDomainTrackJob(job))
        qemuDomainObjSaveJob(driver, obj);
2776
    virCondSignal(&priv->job.cond);
2777 2778
}

2779
void
2780
qemuDomainObjEndAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
2781 2782
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
2783

2784 2785
    priv->jobs_queued--;

2786 2787 2788
    VIR_DEBUG("Stopping async job: %s (vm=%p name=%s)",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
2789

2790
    qemuDomainObjResetAsyncJob(priv);
2791
    qemuDomainObjSaveJob(driver, obj);
2792 2793 2794
    virCondBroadcast(&priv->job.asyncCond);
}

2795 2796 2797 2798 2799
void
qemuDomainObjAbortAsyncJob(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

2800 2801 2802
    VIR_DEBUG("Requesting abort of async job: %s (vm=%p name=%s)",
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              obj, obj->def->name);
2803

2804 2805
    priv->job.abortJob = true;
    virDomainObjBroadcast(obj);
2806 2807
}

2808 2809 2810 2811 2812 2813 2814 2815 2816
/*
 * 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
 */
2817
static int
2818
qemuDomainObjEnterMonitorInternal(virQEMUDriverPtr driver,
2819
                                  virDomainObjPtr obj,
2820
                                  qemuDomainAsyncJob asyncJob)
2821 2822 2823
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

2824
    if (asyncJob != QEMU_ASYNC_JOB_NONE) {
2825 2826 2827
        int ret;
        if ((ret = qemuDomainObjBeginNestedJob(driver, obj, asyncJob)) < 0)
            return ret;
2828
        if (!virDomainObjIsActive(obj)) {
2829 2830
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
2831
            qemuDomainObjEndJob(driver, obj);
2832 2833
            return -1;
        }
2834 2835 2836
    } 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");
2837 2838
    }

2839 2840
    VIR_DEBUG("Entering monitor (mon=%p vm=%p name=%s)",
              priv->mon, obj, obj->def->name);
2841
    virObjectLock(priv->mon);
2842
    virObjectRef(priv->mon);
2843
    ignore_value(virTimeMillisNow(&priv->monStart));
2844
    virObjectUnlock(obj);
2845 2846

    return 0;
2847 2848
}

2849
static void ATTRIBUTE_NONNULL(1)
2850
qemuDomainObjExitMonitorInternal(virQEMUDriverPtr driver,
2851
                                 virDomainObjPtr obj)
2852 2853
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
2854
    bool hasRefs;
2855

2856
    hasRefs = virObjectUnref(priv->mon);
2857

2858
    if (hasRefs)
2859
        virObjectUnlock(priv->mon);
2860

2861
    virObjectLock(obj);
2862 2863
    VIR_DEBUG("Exited monitor (mon=%p vm=%p name=%s)",
              priv->mon, obj, obj->def->name);
2864

2865
    priv->monStart = 0;
2866
    if (!hasRefs)
2867
        priv->mon = NULL;
2868

J
Jiri Denemark 已提交
2869 2870
    if (priv->job.active == QEMU_JOB_ASYNC_NESTED)
        qemuDomainObjEndJob(driver, obj);
2871 2872
}

2873
void qemuDomainObjEnterMonitor(virQEMUDriverPtr driver,
2874
                               virDomainObjPtr obj)
2875
{
2876
    ignore_value(qemuDomainObjEnterMonitorInternal(driver, obj,
2877
                                                   QEMU_ASYNC_JOB_NONE));
2878 2879
}

2880
/* obj must NOT be locked before calling
2881 2882
 *
 * Should be paired with an earlier qemuDomainObjEnterMonitor() call
2883 2884 2885 2886 2887 2888
 *
 * 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.
2889
 */
2890 2891
int qemuDomainObjExitMonitor(virQEMUDriverPtr driver,
                             virDomainObjPtr obj)
2892
{
2893
    qemuDomainObjExitMonitorInternal(driver, obj);
2894
    if (!virDomainObjIsActive(obj)) {
2895 2896 2897
        if (!virGetLastError())
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("domain is no longer running"));
2898 2899 2900
        return -1;
    }
    return 0;
2901
}
2902 2903

/*
2904
 * obj must be locked before calling
2905 2906
 *
 * To be called immediately before any QEMU monitor API call.
2907
 * Must have already either called qemuDomainObjBeginJob()
2908 2909 2910 2911 2912
 * 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
2913 2914 2915
 * 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).
2916 2917
 */
int
2918
qemuDomainObjEnterMonitorAsync(virQEMUDriverPtr driver,
2919
                               virDomainObjPtr obj,
2920
                               qemuDomainAsyncJob asyncJob)
2921
{
2922
    return qemuDomainObjEnterMonitorInternal(driver, obj, asyncJob);
2923 2924
}

D
Daniel P. Berrange 已提交
2925

2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
/**
 * qemuDomainGetAgent:
 * @vm: domain object
 *
 * Returns the agent pointer of @vm;
 */
qemuAgentPtr
qemuDomainGetAgent(virDomainObjPtr vm)
{
    return (((qemuDomainObjPrivatePtr)(vm->privateData))->agent);
}

D
Daniel P. Berrange 已提交
2938

2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
/*
 * 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 已提交
2950 2951 2952
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

2953 2954
    VIR_DEBUG("Entering agent (agent=%p vm=%p name=%s)",
              priv->agent, obj, obj->def->name);
2955
    virObjectLock(priv->agent);
2956
    virObjectRef(priv->agent);
D
Daniel P. Berrange 已提交
2957
    ignore_value(virTimeMillisNow(&priv->agentStart));
2958
    virObjectUnlock(obj);
D
Daniel P. Berrange 已提交
2959 2960
}

2961 2962 2963 2964 2965 2966 2967

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

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

2974
    if (hasRefs)
2975
        virObjectUnlock(priv->agent);
D
Daniel P. Berrange 已提交
2976

2977
    virObjectLock(obj);
2978 2979
    VIR_DEBUG("Exited agent (agent=%p vm=%p name=%s)",
              priv->agent, obj, obj->def->name);
D
Daniel P. Berrange 已提交
2980 2981

    priv->agentStart = 0;
2982
    if (!hasRefs)
D
Daniel P. Berrange 已提交
2983 2984 2985
        priv->agent = NULL;
}

2986
void qemuDomainObjEnterRemote(virDomainObjPtr obj)
2987
{
2988 2989
    VIR_DEBUG("Entering remote (vm=%p name=%s)",
              obj, obj->def->name);
2990
    virObjectUnlock(obj);
2991 2992
}

2993
void qemuDomainObjExitRemote(virDomainObjPtr obj)
2994
{
2995
    virObjectLock(obj);
2996 2997
    VIR_DEBUG("Exited remote (vm=%p name=%s)",
              obj, obj->def->name);
2998
}
2999 3000


3001 3002 3003 3004 3005 3006 3007 3008
virDomainDefPtr
qemuDomainDefCopy(virQEMUDriverPtr driver,
                  virDomainDefPtr src,
                  unsigned int flags)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    virDomainDefPtr ret = NULL;
    virCapsPtr caps = NULL;
3009
    char *xml = NULL;
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019

    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,
3020 3021
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                        VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
3022 3023
        goto cleanup;

3024
 cleanup:
3025 3026 3027 3028 3029
    VIR_FREE(xml);
    virObjectUnref(caps);
    return ret;
}

3030
int
3031
qemuDomainDefFormatBuf(virQEMUDriverPtr driver,
3032 3033 3034
                       virDomainDefPtr def,
                       unsigned int flags,
                       virBuffer *buf)
3035
{
3036
    int ret = -1;
3037
    virCPUDefPtr cpu = NULL;
3038
    virCPUDefPtr def_cpu = def->cpu;
3039 3040
    virDomainControllerDefPtr *controllers = NULL;
    int ncontrollers = 0;
3041 3042 3043 3044
    virCapsPtr caps = NULL;

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

    /* Update guest CPU requirements according to host CPU */
3047 3048 3049
    if ((flags & VIR_DOMAIN_XML_UPDATE_CPU) &&
        def_cpu &&
        (def_cpu->mode != VIR_CPU_MODE_CUSTOM || def_cpu->model)) {
3050 3051
        if (!caps->host.cpu ||
            !caps->host.cpu->model) {
3052 3053
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("cannot get host CPU capabilities"));
3054 3055 3056
            goto cleanup;
        }

3057
        if (!(cpu = virCPUDefCopy(def_cpu)) ||
3058
            cpuUpdate(cpu, caps->host.cpu) < 0)
3059 3060 3061 3062
            goto cleanup;
        def->cpu = cpu;
    }

3063
    if ((flags & VIR_DOMAIN_XML_MIGRATABLE)) {
3064
        size_t i;
3065
        int toremove = 0;
3066
        virDomainControllerDefPtr usb = NULL, pci = NULL;
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081

        /* 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];
            }
        }
3082 3083 3084 3085
        /*  The original purpose of the check was the migration compatibility
         *  with libvirt <= 0.9.4. Limitation doesn't apply to other archs
         *  and can cause problems on PPC64.
         */
3086 3087
        if (ARCH_IS_X86(def->os.arch) && qemuDomainMachineIsI440FX(def) &&
            usb && usb->idx == 0 && usb->model == -1) {
3088 3089
            VIR_DEBUG("Removing default USB controller from domain '%s'"
                      " for migration compatibility", def->name);
3090
            toremove++;
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
        } 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 已提交
3109
            VIR_DEBUG("Removing default pci-root from domain '%s'"
3110
                      " for migration compatibility", def->name);
3111
            toremove++;
3112 3113 3114 3115
        } else {
            pci = NULL;
        }

3116
        if (toremove) {
3117 3118
            controllers = def->controllers;
            ncontrollers = def->ncontrollers;
3119
            if (VIR_ALLOC_N(def->controllers, ncontrollers - toremove) < 0) {
3120 3121 3122 3123 3124 3125
                controllers = NULL;
                goto cleanup;
            }

            def->ncontrollers = 0;
            for (i = 0; i < ncontrollers; i++) {
3126
                if (controllers[i] != usb && controllers[i] != pci)
3127 3128 3129
                    def->controllers[def->ncontrollers++] = controllers[i];
            }
        }
3130 3131


3132 3133
    }

3134
    ret = virDomainDefFormatInternal(def, driver->caps,
3135 3136
                                     virDomainDefFormatConvertXMLFlags(flags),
                                     buf);
3137

3138
 cleanup:
3139 3140
    def->cpu = def_cpu;
    virCPUDefFree(cpu);
3141 3142 3143 3144 3145
    if (controllers) {
        VIR_FREE(def->controllers);
        def->controllers = controllers;
        def->ncontrollers = ncontrollers;
    }
3146
    virObjectUnref(caps);
3147 3148
    return ret;
}
3149

3150
char *qemuDomainDefFormatXML(virQEMUDriverPtr driver,
3151
                             virDomainDefPtr def,
3152
                             unsigned int flags)
3153 3154 3155
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3156
    if (qemuDomainDefFormatBuf(driver, def, flags, &buf) < 0) {
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
        virBufferFreeAndReset(&buf);
        return NULL;
    }

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

    return virBufferContentAndReset(&buf);
}

3170
char *qemuDomainFormatXML(virQEMUDriverPtr driver,
3171
                          virDomainObjPtr vm,
3172
                          unsigned int flags)
3173 3174 3175 3176 3177 3178 3179 3180
{
    virDomainDefPtr def;

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

3181
    return qemuDomainDefFormatXML(driver, def, flags);
3182 3183
}

3184
char *
3185
qemuDomainDefFormatLive(virQEMUDriverPtr driver,
3186
                        virDomainDefPtr def,
3187 3188
                        bool inactive,
                        bool compatible)
3189 3190 3191 3192 3193
{
    unsigned int flags = QEMU_DOMAIN_FORMAT_LIVE_FLAGS;

    if (inactive)
        flags |= VIR_DOMAIN_XML_INACTIVE;
3194 3195
    if (compatible)
        flags |= VIR_DOMAIN_XML_MIGRATABLE;
3196

3197
    return qemuDomainDefFormatXML(driver, def, flags);
3198 3199
}

3200

3201
void qemuDomainObjTaint(virQEMUDriverPtr driver,
3202
                        virDomainObjPtr obj,
3203
                        virDomainTaintFlags taint,
3204
                        qemuDomainLogContextPtr logCtxt)
3205
{
3206
    virErrorPtr orig_err = NULL;
3207
    bool closeLog = false;
3208

3209 3210 3211 3212 3213 3214 3215 3216 3217
    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));
3218 3219 3220 3221 3222

        /* We don't care about errors logging taint info, so
         * preserve original error, and clear any error that
         * is raised */
        orig_err = virSaveLastError();
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
        if (logCtxt == NULL) {
            logCtxt = qemuDomainLogContextNew(driver, obj,
                                              QEMU_DOMAIN_LOG_CONTEXT_MODE_ATTACH);
            if (!logCtxt) {
                if (orig_err) {
                    virSetError(orig_err);
                    virFreeError(orig_err);
                }
                VIR_WARN("Unable to open domainlog");
                return;
            }
            closeLog = true;
        }

        if (qemuDomainLogContextWrite(logCtxt,
                                      "Domain id=%d is tainted: %s\n",
                                      obj->def->id,
                                      virDomainTaintTypeToString(taint)) < 0)
3241
            virResetLastError();
3242 3243
        if (closeLog)
            qemuDomainLogContextFree(logCtxt);
3244 3245 3246 3247
        if (orig_err) {
            virSetError(orig_err);
            virFreeError(orig_err);
        }
3248 3249 3250 3251
    }
}


3252
void qemuDomainObjCheckTaint(virQEMUDriverPtr driver,
3253
                             virDomainObjPtr obj,
3254
                             qemuDomainLogContextPtr logCtxt)
3255
{
3256
    size_t i;
3257
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3258
    qemuDomainObjPrivatePtr priv = obj->privateData;
3259

3260
    if (virQEMUDriverIsPrivileged(driver) &&
3261 3262 3263
        (!cfg->clearEmulatorCapabilities ||
         cfg->user == 0 ||
         cfg->group == 0))
3264
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES, logCtxt);
3265

3266
    if (priv->hookRun)
3267
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOOK, logCtxt);
3268

3269 3270 3271
    if (obj->def->namespaceData) {
        qemuDomainCmdlineDefPtr qemucmd = obj->def->namespaceData;
        if (qemucmd->num_args || qemucmd->num_env)
3272
            qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_ARGV, logCtxt);
3273 3274
    }

3275
    if (obj->def->cpu && obj->def->cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH)
3276
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOST_CPU, logCtxt);
3277

3278
    for (i = 0; i < obj->def->ndisks; i++)
3279
        qemuDomainObjCheckDiskTaint(driver, obj, obj->def->disks[i], logCtxt);
3280

3281 3282
    for (i = 0; i < obj->def->nhostdevs; i++)
        qemuDomainObjCheckHostdevTaint(driver, obj, obj->def->hostdevs[i],
3283
                                       logCtxt);
3284

3285
    for (i = 0; i < obj->def->nnets; i++)
3286
        qemuDomainObjCheckNetTaint(driver, obj, obj->def->nets[i], logCtxt);
3287

3288
    if (obj->def->os.dtb)
3289
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_DTB, logCtxt);
3290

3291
    virObjectUnref(cfg);
3292 3293 3294
}


3295
void qemuDomainObjCheckDiskTaint(virQEMUDriverPtr driver,
3296
                                 virDomainObjPtr obj,
3297
                                 virDomainDiskDefPtr disk,
3298
                                 qemuDomainLogContextPtr logCtxt)
3299
{
3300
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3301
    int format = virDomainDiskGetFormat(disk);
3302

3303
    if ((!format || format == VIR_STORAGE_FILE_AUTO) &&
3304
        cfg->allowDiskFormatProbing)
3305
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_DISK_PROBING, logCtxt);
3306

3307 3308
    if (disk->rawio == VIR_TRISTATE_BOOL_YES)
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES,
3309
                           logCtxt);
3310

3311 3312 3313 3314
    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,
3315
                           logCtxt);
3316

3317
    virObjectUnref(cfg);
3318 3319 3320
}


3321 3322 3323
void qemuDomainObjCheckHostdevTaint(virQEMUDriverPtr driver,
                                    virDomainObjPtr obj,
                                    virDomainHostdevDefPtr hostdev,
3324
                                    qemuDomainLogContextPtr logCtxt)
3325 3326 3327 3328 3329 3330
{
    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,
3331
                               logCtxt);
3332 3333 3334
}


3335
void qemuDomainObjCheckNetTaint(virQEMUDriverPtr driver,
3336
                                virDomainObjPtr obj,
3337
                                virDomainNetDefPtr net,
3338
                                qemuDomainLogContextPtr logCtxt)
3339
{
3340 3341 3342 3343 3344 3345
    /* 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)
3346
        qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_SHELL_SCRIPTS, logCtxt);
3347
}
3348 3349


3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
qemuDomainLogContextPtr qemuDomainLogContextNew(virQEMUDriverPtr driver,
                                                virDomainObjPtr vm,
                                                qemuDomainLogContextMode mode)
{
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    qemuDomainLogContextPtr ctxt = NULL;

    if (VIR_ALLOC(ctxt) < 0)
        goto error;

3360
    VIR_DEBUG("Context new %p stdioLogD=%d", ctxt, cfg->stdioLogD);
3361 3362 3363 3364
    ctxt->writefd = -1;
    ctxt->readfd = -1;
    virAtomicIntSet(&ctxt->refs, 1);

3365 3366 3367
    if (virAsprintf(&ctxt->path, "%s/%s.log", cfg->logDir, vm->def->name) < 0)
        goto error;

3368 3369 3370 3371
    if (cfg->stdioLogD) {
        ctxt->manager = virLogManagerNew(virQEMUDriverIsPrivileged(driver));
        if (!ctxt->manager)
            goto error;
3372

3373 3374 3375 3376
        ctxt->writefd = virLogManagerDomainOpenLogFile(ctxt->manager,
                                                       "qemu",
                                                       vm->def->uuid,
                                                       vm->def->name,
3377
                                                       ctxt->path,
3378 3379 3380 3381 3382 3383
                                                       0,
                                                       &ctxt->inode,
                                                       &ctxt->pos);
        if (ctxt->writefd < 0)
            goto error;
    } else {
3384
        if ((ctxt->writefd = open(ctxt->path, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)) < 0) {
3385
            virReportSystemError(errno, _("failed to create logfile %s"),
3386
                                 ctxt->path);
3387 3388
            goto error;
        }
3389
        if (virSetCloseExec(ctxt->writefd) < 0) {
3390
            virReportSystemError(errno, _("failed to set close-on-exec flag on %s"),
3391
                                 ctxt->path);
3392 3393 3394
            goto error;
        }

3395 3396 3397 3398 3399 3400 3401
        /* For unprivileged startup we must truncate the file since
         * we can't rely on logrotate. We don't use O_TRUNC since
         * it is better for SELinux policy if we truncate afterwards */
        if (mode == QEMU_DOMAIN_LOG_CONTEXT_MODE_START &&
            !virQEMUDriverIsPrivileged(driver) &&
            ftruncate(ctxt->writefd, 0) < 0) {
            virReportSystemError(errno, _("failed to truncate %s"),
3402
                                 ctxt->path);
3403 3404 3405 3406
            goto error;
        }

        if (mode == QEMU_DOMAIN_LOG_CONTEXT_MODE_START) {
3407
            if ((ctxt->readfd = open(ctxt->path, O_RDONLY, S_IRUSR | S_IWUSR)) < 0) {
3408
                virReportSystemError(errno, _("failed to open logfile %s"),
3409
                                     ctxt->path);
3410 3411 3412 3413
                goto error;
            }
            if (virSetCloseExec(ctxt->readfd) < 0) {
                virReportSystemError(errno, _("failed to set close-on-exec flag on %s"),
3414
                                     ctxt->path);
3415 3416 3417 3418
                goto error;
            }
        }

3419 3420
        if ((ctxt->pos = lseek(ctxt->writefd, 0, SEEK_END)) < 0) {
            virReportSystemError(errno, _("failed to seek in log file %s"),
3421
                                 ctxt->path);
3422 3423 3424 3425
            goto error;
        }
    }

3426
 cleanup:
3427 3428 3429 3430 3431
    virObjectUnref(cfg);
    return ctxt;

 error:
    qemuDomainLogContextFree(ctxt);
3432 3433
    ctxt = NULL;
    goto cleanup;
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
}


int qemuDomainLogContextWrite(qemuDomainLogContextPtr ctxt,
                              const char *fmt, ...)
{
    va_list argptr;
    char *message = NULL;
    int ret = -1;

    va_start(argptr, fmt);

    if (virVasprintf(&message, fmt, argptr) < 0)
        goto cleanup;
3448 3449
    if (!ctxt->manager &&
        lseek(ctxt->writefd, 0, SEEK_END) < 0) {
3450
        virReportSystemError(errno, "%s",
3451
                             _("Unable to seek to end of domain logfile"));
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
        goto cleanup;
    }
    if (safewrite(ctxt->writefd, message, strlen(message)) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to write to domain logfile"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    va_end(argptr);
    VIR_FREE(message);
    return ret;
}


ssize_t qemuDomainLogContextRead(qemuDomainLogContextPtr ctxt,
                                 char **msg)
{
3472 3473 3474 3475
    VIR_DEBUG("Context read %p manager=%p inode=%llu pos=%llu",
              ctxt, ctxt->manager,
              (unsigned long long)ctxt->inode,
              (unsigned long long)ctxt->pos);
3476
    char *buf;
3477 3478 3479
    size_t buflen;
    if (ctxt->manager) {
        buf = virLogManagerDomainReadLogFile(ctxt->manager,
3480
                                             ctxt->path,
3481 3482 3483 3484 3485 3486 3487 3488 3489
                                             ctxt->inode,
                                             ctxt->pos,
                                             1024 * 128,
                                             0);
        if (!buf)
            return -1;
        buflen = strlen(buf);
    } else {
        ssize_t got;
3490

3491
        buflen = 1024 * 128;
3492

3493 3494
        /* Best effort jump to start of messages */
        ignore_value(lseek(ctxt->readfd, ctxt->pos, SEEK_SET));
3495

3496 3497
        if (VIR_ALLOC_N(buf, buflen) < 0)
            return -1;
3498

3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
        got = saferead(ctxt->readfd, buf, buflen - 1);
        if (got < 0) {
            VIR_FREE(buf);
            virReportSystemError(errno, "%s",
                                 _("Unable to read from log file"));
            return -1;
        }

        buf[got] = '\0';

        ignore_value(VIR_REALLOC_N_QUIET(buf, got + 1));
        buflen = got;
    }
3512 3513 3514

    *msg = buf;

3515
    return buflen;
3516 3517 3518
}


3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 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
/**
 * qemuDomainLogAppendMessage:
 *
 * This is a best-effort attempt to add a log message to the qemu log file
 * either by using virtlogd or the legacy approach */
int
qemuDomainLogAppendMessage(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           const char *fmt,
                           ...)
{
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    virLogManagerPtr manager = NULL;
    va_list ap;
    char *path = NULL;
    int writefd = -1;
    char *message = NULL;
    int ret = -1;

    va_start(ap, fmt);

    if (virVasprintf(&message, fmt, ap) < 0)
        goto cleanup;

    VIR_DEBUG("Append log message (vm='%s' message='%s) stdioLogD=%d",
              vm->def->name, message, cfg->stdioLogD);

    if (virAsprintf(&path, "%s/%s.log", cfg->logDir, vm->def->name) < 0)
        goto cleanup;

    if (cfg->stdioLogD) {
        if (!(manager = virLogManagerNew(virQEMUDriverIsPrivileged(driver))))
            goto cleanup;

        if (virLogManagerDomainAppendMessage(manager, "qemu", vm->def->uuid,
                                             vm->def->name, path, message, 0) < 0)
            goto cleanup;
    } else {
        if ((writefd = open(path, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)) < 0) {
            virReportSystemError(errno, _("failed to create logfile %s"),
                                 path);
            goto cleanup;
        }

        if (safewrite(writefd, message, strlen(message)) < 0)
            goto cleanup;
    }

    ret = 0;

 cleanup:
    va_end(ap);
    VIR_FREE(message);
    VIR_FORCE_CLOSE(writefd);
    virLogManagerFree(manager);
    virObjectUnref(cfg);
    VIR_FREE(path);

    return ret;
}


3581 3582 3583 3584 3585 3586 3587 3588
int qemuDomainLogContextGetWriteFD(qemuDomainLogContextPtr ctxt)
{
    return ctxt->writefd;
}


void qemuDomainLogContextMarkPosition(qemuDomainLogContextPtr ctxt)
{
3589 3590
    if (ctxt->manager)
        virLogManagerDomainGetLogFilePosition(ctxt->manager,
3591
                                              ctxt->path,
3592 3593 3594 3595 3596
                                              0,
                                              &ctxt->inode,
                                              &ctxt->pos);
    else
        ctxt->pos = lseek(ctxt->writefd, 0, SEEK_END);
3597 3598 3599 3600 3601
}


void qemuDomainLogContextRef(qemuDomainLogContextPtr ctxt)
{
3602
    VIR_DEBUG("Context ref %p", ctxt);
3603 3604 3605 3606
    virAtomicIntInc(&ctxt->refs);
}


3607 3608 3609 3610 3611 3612
virLogManagerPtr qemuDomainLogContextGetManager(qemuDomainLogContextPtr ctxt)
{
    return ctxt->manager;
}


3613 3614 3615 3616 3617 3618 3619 3620
void qemuDomainLogContextFree(qemuDomainLogContextPtr ctxt)
{
    bool lastRef;

    if (!ctxt)
        return;

    lastRef = virAtomicIntDecAndTest(&ctxt->refs);
3621
    VIR_DEBUG("Context free %p lastref=%d", ctxt, lastRef);
3622 3623 3624
    if (!lastRef)
        return;

3625
    virLogManagerFree(ctxt->manager);
3626
    VIR_FREE(ctxt->path);
3627 3628 3629 3630 3631 3632
    VIR_FORCE_CLOSE(ctxt->writefd);
    VIR_FORCE_CLOSE(ctxt->readfd);
    VIR_FREE(ctxt);
}


3633 3634
/* Locate an appropriate 'qemu-img' binary.  */
const char *
3635
qemuFindQemuImgBinary(virQEMUDriverPtr driver)
3636
{
3637 3638
    if (!driver->qemuImgBinary)
        virReportError(VIR_ERR_INTERNAL_ERROR,
3639
                       "%s", _("unable to find qemu-img"));
3640 3641 3642 3643 3644 3645 3646

    return driver->qemuImgBinary;
}

int
qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                virDomainSnapshotObjPtr snapshot,
3647
                                virCapsPtr caps,
3648 3649 3650 3651 3652 3653 3654 3655 3656
                                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);
3657
    newxml = virDomainSnapshotDefFormat(
3658
        uuidstr, snapshot->def, caps,
3659 3660
        virDomainDefFormatConvertXMLFlags(QEMU_DOMAIN_FORMAT_LIVE_FLAGS),
        1);
3661
    if (newxml == NULL)
3662 3663
        return -1;

3664
    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0)
3665 3666 3667 3668 3669 3670 3671
        goto cleanup;
    if (virFileMakePath(snapDir) < 0) {
        virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
                             snapDir);
        goto cleanup;
    }

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

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

3677
 cleanup:
3678 3679 3680 3681 3682 3683 3684 3685
    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.  */
3686
static int
3687
qemuDomainSnapshotForEachQcow2Raw(virQEMUDriverPtr driver,
3688 3689 3690 3691 3692
                                  virDomainDefPtr def,
                                  const char *name,
                                  const char *op,
                                  bool try_all,
                                  int ndisks)
3693 3694
{
    const char *qemuimgarg[] = { NULL, "snapshot", NULL, NULL, NULL, NULL };
3695
    size_t i;
3696 3697 3698 3699 3700 3701 3702 3703 3704
    bool skipped = false;

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

    qemuimgarg[2] = op;
3705
    qemuimgarg[3] = name;
3706

3707
    for (i = 0; i < ndisks; i++) {
3708
        /* FIXME: we also need to handle LVM here */
3709
        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
3710 3711 3712
            int format = virDomainDiskGetFormat(def->disks[i]);

            if (format > 0 && format != VIR_STORAGE_FILE_QCOW2) {
3713 3714 3715 3716 3717
                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",
3718
                             def->disks[i]->dst);
3719 3720
                    skipped = true;
                    continue;
3721 3722 3723 3724 3725
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
3726
                }
3727 3728 3729 3730
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Disk device '%s' does not support"
                                 " snapshotting"),
                               def->disks[i]->dst);
3731 3732 3733
                return -1;
            }

3734
            qemuimgarg[4] = virDomainDiskGetSource(def->disks[i]);
3735 3736 3737 3738

            if (virRun(qemuimgarg, NULL) < 0) {
                if (try_all) {
                    VIR_WARN("skipping snapshot action on %s",
3739
                             def->disks[i]->dst);
3740 3741
                    skipped = true;
                    continue;
3742 3743 3744 3745 3746
                } else if (STREQ(op, "-c") && i) {
                    /* We must roll back partial creation by deleting
                     * all earlier snapshots.  */
                    qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
                                                      "-d", false, i);
3747 3748 3749 3750 3751 3752 3753 3754 3755
                }
                return -1;
            }
        }
    }

    return skipped ? 1 : 0;
}

3756 3757 3758
/* 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
3759
qemuDomainSnapshotForEachQcow2(virQEMUDriverPtr driver,
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
                               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);
}

3776 3777
/* Discard one snapshot (or its metadata), without reparenting any children.  */
int
3778
qemuDomainSnapshotDiscard(virQEMUDriverPtr driver,
3779 3780 3781 3782 3783 3784 3785 3786 3787
                          virDomainObjPtr vm,
                          virDomainSnapshotObjPtr snap,
                          bool update_current,
                          bool metadata_only)
{
    char *snapFile = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap = NULL;
3788
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3789 3790 3791 3792 3793 3794 3795 3796 3797

    if (!metadata_only) {
        if (!virDomainObjIsActive(vm)) {
            /* Ignore any skipped disks */
            if (qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-d",
                                               true) < 0)
                goto cleanup;
        } else {
            priv = vm->privateData;
3798
            qemuDomainObjEnterMonitor(driver, vm);
3799 3800
            /* we continue on even in the face of error */
            qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
3801
            ignore_value(qemuDomainObjExitMonitor(driver, vm));
3802 3803 3804
        }
    }

3805
    if (virAsprintf(&snapFile, "%s/%s/%s.xml", cfg->snapshotDir,
3806
                    vm->def->name, snap->def->name) < 0)
3807 3808 3809 3810
        goto cleanup;

    if (snap == vm->current_snapshot) {
        if (update_current && snap->def->parent) {
3811
            parentsnap = virDomainSnapshotFindByName(vm->snapshots,
3812 3813 3814 3815 3816 3817
                                                     snap->def->parent);
            if (!parentsnap) {
                VIR_WARN("missing parent snapshot matching name '%s'",
                         snap->def->parent);
            } else {
                parentsnap->def->current = true;
3818
                if (qemuDomainSnapshotWriteMetadata(vm, parentsnap, driver->caps,
3819
                                                    cfg->snapshotDir) < 0) {
3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
                    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);
3832
    virDomainSnapshotObjListRemove(vm->snapshots, snap);
3833 3834 3835

    ret = 0;

3836
 cleanup:
3837
    VIR_FREE(snapFile);
3838
    virObjectUnref(cfg);
3839 3840 3841 3842
    return ret;
}

/* Hash iterator callback to discard multiple snapshots.  */
3843 3844 3845
int qemuDomainSnapshotDiscardAll(void *payload,
                                 const void *name ATTRIBUTE_UNUSED,
                                 void *data)
3846 3847
{
    virDomainSnapshotObjPtr snap = payload;
3848
    virQEMUSnapRemovePtr curr = data;
3849 3850 3851 3852 3853 3854 3855 3856
    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;
3857
    return 0;
3858 3859 3860
}

int
3861
qemuDomainSnapshotDiscardAllMetadata(virQEMUDriverPtr driver,
3862 3863
                                     virDomainObjPtr vm)
{
3864
    virQEMUSnapRemove rem;
3865 3866 3867 3868 3869

    rem.driver = driver;
    rem.vm = vm;
    rem.metadata_only = true;
    rem.err = 0;
3870 3871
    virDomainSnapshotForEach(vm->snapshots, qemuDomainSnapshotDiscardAll,
                             &rem);
3872 3873 3874 3875 3876

    return rem.err;
}

/*
3877
 * The caller must hold a lock the vm.
3878 3879
 */
void
3880
qemuDomainRemoveInactive(virQEMUDriverPtr driver,
3881 3882
                         virDomainObjPtr vm)
{
3883
    bool haveJob = true;
3884
    char *snapDir;
3885 3886 3887 3888 3889 3890 3891 3892
    virQEMUDriverConfigPtr cfg;

    if (vm->persistent) {
        /* Short-circuit, we don't want to remove a persistent domain */
        return;
    }

    cfg = virQEMUDriverGetConfig(driver);
3893

3894 3895 3896
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        haveJob = false;

3897 3898 3899 3900 3901
    /* 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);
    }
3902
    else if (virAsprintf(&snapDir, "%s/%s", cfg->snapshotDir,
3903 3904
                         vm->def->name) < 0) {
        VIR_WARN("unable to remove snapshot directory %s/%s",
3905
                 cfg->snapshotDir, vm->def->name);
3906 3907 3908 3909 3910
    } else {
        if (rmdir(snapDir) < 0 && errno != ENOENT)
            VIR_WARN("unable to remove snapshot directory %s", snapDir);
        VIR_FREE(snapDir);
    }
3911 3912 3913

    virObjectRef(vm);

3914
    virDomainObjListRemove(driver->domains, vm);
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
    /*
     * 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);
3928
    virObjectUnref(cfg);
3929 3930

    if (haveJob)
3931
        qemuDomainObjEndJob(driver, vm);
3932 3933

    virObjectUnref(vm);
3934
}
3935 3936

void
3937
qemuDomainSetFakeReboot(virQEMUDriverPtr driver,
3938 3939 3940 3941
                        virDomainObjPtr vm,
                        bool value)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3942
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3943 3944

    if (priv->fakeReboot == value)
3945
        goto cleanup;
3946 3947 3948

    priv->fakeReboot = value;

3949
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0)
3950
        VIR_WARN("Failed to save status on vm %s", vm->def->name);
3951

3952
 cleanup:
3953
    virObjectUnref(cfg);
3954
}
M
Michal Privoznik 已提交
3955

3956
static void
3957 3958
qemuDomainCheckRemoveOptionalDisk(virQEMUDriverPtr driver,
                                  virDomainObjPtr vm,
3959
                                  size_t diskIndex)
3960 3961
{
    char uuid[VIR_UUID_STRING_BUFLEN];
3962
    virObjectEventPtr event = NULL;
3963
    virDomainDiskDefPtr disk = vm->def->disks[diskIndex];
3964
    const char *src = virDomainDiskGetSource(disk);
3965 3966 3967 3968 3969

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

    VIR_DEBUG("Dropping disk '%s' on domain '%s' (UUID '%s') "
              "due to inaccessible source '%s'",
3970
              disk->dst, vm->def->name, uuid, src);
3971 3972 3973 3974

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

3975
        event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
3976 3977
                                                   disk->info.alias,
                                                   VIR_DOMAIN_EVENT_DISK_CHANGE_MISSING_ON_START);
3978
        ignore_value(virDomainDiskSetSource(disk, NULL));
3979
    } else {
3980
        event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
3981 3982
                                                   disk->info.alias,
                                                   VIR_DOMAIN_EVENT_DISK_DROP_MISSING_ON_START);
3983 3984
        virDomainDiskRemove(vm->def, diskIndex);
        virDomainDiskDefFree(disk);
3985 3986
    }

3987
    qemuDomainEventQueue(driver, event);
3988 3989
}

3990 3991 3992
static int
qemuDomainCheckDiskStartupPolicy(virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
3993
                                 size_t diskIndex,
3994 3995
                                 bool cold_boot)
{
3996
    int startupPolicy = vm->def->disks[diskIndex]->startupPolicy;
3997
    int device = vm->def->disks[diskIndex]->device;
3998

3999
    switch ((virDomainStartupPolicy) startupPolicy) {
4000
        case VIR_DOMAIN_STARTUP_POLICY_OPTIONAL:
4001 4002 4003 4004 4005 4006
            /* 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)
4007
                return -1;
4008 4009 4010
            break;

        case VIR_DOMAIN_STARTUP_POLICY_MANDATORY:
4011
            return -1;
4012 4013

        case VIR_DOMAIN_STARTUP_POLICY_REQUISITE:
4014
            if (cold_boot)
4015
                return -1;
4016 4017 4018 4019 4020 4021 4022 4023
            break;

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

4024
    qemuDomainCheckRemoveOptionalDisk(driver, vm, diskIndex);
4025 4026 4027 4028

    return 0;
}

4029

M
Michal Privoznik 已提交
4030
int
4031
qemuDomainCheckDiskPresence(virQEMUDriverPtr driver,
M
Michal Privoznik 已提交
4032
                            virDomainObjPtr vm,
4033
                            bool cold_boot)
M
Michal Privoznik 已提交
4034 4035
{
    int ret = -1;
4036
    size_t i;
M
Michal Privoznik 已提交
4037

4038
    VIR_DEBUG("Checking for disk presence");
4039
    for (i = vm->def->ndisks; i > 0; i--) {
4040 4041
        size_t idx = i - 1;
        virDomainDiskDefPtr disk = vm->def->disks[idx];
4042
        virStorageFileFormat format = virDomainDiskGetFormat(disk);
M
Michal Privoznik 已提交
4043

4044
        if (virStorageSourceIsEmpty(disk->src))
4045 4046 4047 4048 4049
            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 */
4050
        if (virStorageSourceIsLocalStorage(disk->src) &&
4051
            format > VIR_STORAGE_FILE_NONE &&
4052
            format < VIR_STORAGE_FILE_BACKING &&
4053
            virFileExists(virDomainDiskGetSource(disk)))
M
Michal Privoznik 已提交
4054 4055
            continue;

4056
        if (qemuDomainDetermineDiskChain(driver, vm, disk, true, true) >= 0)
M
Michal Privoznik 已提交
4057
            continue;
4058

4059
        if (disk->startupPolicy &&
4060
            qemuDomainCheckDiskStartupPolicy(driver, vm, idx,
4061 4062 4063
                                             cold_boot) >= 0) {
            virResetLastError();
            continue;
M
Michal Privoznik 已提交
4064 4065
        }

4066
        goto error;
M
Michal Privoznik 已提交
4067 4068 4069 4070
    }

    ret = 0;

4071
 error:
M
Michal Privoznik 已提交
4072 4073
    return ret;
}
4074 4075 4076 4077 4078 4079 4080 4081 4082 4083

/*
 * The vm must be locked when any of the following cleanup functions is
 * called.
 */
int
qemuDomainCleanupAdd(virDomainObjPtr vm,
                     qemuDomainCleanupCallback cb)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
4084
    size_t i;
4085 4086 4087 4088 4089 4090 4091 4092 4093 4094

    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,
4095
                     priv->ncleanupCallbacks, 1) < 0)
4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106
        return -1;

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

void
qemuDomainCleanupRemove(virDomainObjPtr vm,
                        qemuDomainCleanupCallback cb)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
4107
    size_t i;
4108 4109 4110 4111

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

    for (i = 0; i < priv->ncleanupCallbacks; i++) {
4112 4113 4114
        if (priv->cleanupCallbacks[i] == cb)
            VIR_DELETE_ELEMENT_INPLACE(priv->cleanupCallbacks,
                                       i, priv->ncleanupCallbacks);
4115 4116 4117 4118 4119 4120 4121 4122
    }

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

void
4123
qemuDomainCleanupRun(virQEMUDriverPtr driver,
4124 4125 4126
                     virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
4127
    size_t i;
4128 4129 4130 4131

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

    /* run cleanup callbacks in reverse order */
4132 4133
    for (i = 0; i < priv->ncleanupCallbacks; i++) {
        if (priv->cleanupCallbacks[priv->ncleanupCallbacks - (i + 1)])
4134 4135 4136 4137 4138 4139 4140
            priv->cleanupCallbacks[i](driver, vm);
    }

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

4142 4143 4144
static void
qemuDomainGetImageIds(virQEMUDriverConfigPtr cfg,
                      virDomainObjPtr vm,
4145
                      virStorageSourcePtr src,
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
                      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;
    }

4164 4165
    if (vm && (vmlabel = virDomainDefGetSecurityLabelDef(vm->def, "dac")) &&
        vmlabel->label)
4166 4167
        virParseOwnershipIds(vmlabel->label, uid, gid);

4168
    if ((disklabel = virStorageSourceGetSecurityLabelDef(src, "dac")) &&
4169
        disklabel->label)
4170 4171 4172 4173
        virParseOwnershipIds(disklabel->label, uid, gid);
}


4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
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;
}


4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212
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;
}


4213
int
4214
qemuDomainDetermineDiskChain(virQEMUDriverPtr driver,
4215
                             virDomainObjPtr vm,
4216
                             virDomainDiskDefPtr disk,
4217 4218
                             bool force_probe,
                             bool report_broken)
4219
{
4220 4221
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    int ret = 0;
4222 4223
    uid_t uid;
    gid_t gid;
4224

4225
    if (virStorageSourceIsEmpty(disk->src))
4226
        goto cleanup;
4227

4228
    if (disk->src->backingStore) {
4229
        if (force_probe)
4230
            virStorageSourceBackingStoreClear(disk->src);
4231
        else
4232
            goto cleanup;
4233
    }
4234

4235
    qemuDomainGetImageIds(cfg, vm, disk->src, &uid, &gid);
4236

4237
    if (virStorageFileGetMetadata(disk->src,
4238
                                  uid, gid,
4239
                                  cfg->allowDiskFormatProbing,
4240
                                  report_broken) < 0)
4241 4242
        ret = -1;

4243
 cleanup:
4244 4245
    virObjectUnref(cfg);
    return ret;
4246
}
4247

4248

4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
/**
 * qemuDomainDiskChainElementRevoke:
 *
 * Revoke access to a single backing chain element. This restores the labels,
 * removes cgroup ACLs for devices and removes locks.
 */
void
qemuDomainDiskChainElementRevoke(virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
                                 virStorageSourcePtr elem)
{
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
                                            vm->def, elem) < 0)
        VIR_WARN("Unable to restore security label on %s", NULLSTR(elem->path));

    if (qemuTeardownImageCgroup(vm, elem) < 0)
        VIR_WARN("Failed to teardown cgroup for disk path %s",
                 NULLSTR(elem->path));

    if (virDomainLockImageDetach(driver->lockManager, vm, elem) < 0)
        VIR_WARN("Unable to release lock on %s", NULLSTR(elem->path));
}


/**
 * qemuDomainDiskChainElementPrepare:
 *
 * Allow a VM access to a single element of a disk backing chain; this helper
 * ensures that the lock manager, cgroup device controller, and security manager
 * labelling are all aware of each new file before it is added to a chain */
int
qemuDomainDiskChainElementPrepare(virQEMUDriverPtr driver,
                                  virDomainObjPtr vm,
                                  virStorageSourcePtr elem,
                                  bool readonly)
{
    bool was_readonly = elem->readonly;
    virQEMUDriverConfigPtr cfg = NULL;
    int ret = -1;

    cfg = virQEMUDriverGetConfig(driver);

    elem->readonly = readonly;

    if (virDomainLockImageAttach(driver->lockManager, cfg->uri, vm, elem) < 0)
        goto cleanup;

    if (qemuSetupImageCgroup(vm, elem) < 0)
        goto cleanup;

    if (virSecurityManagerSetImageLabel(driver->securityManager, vm->def,
                                        elem) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    elem->readonly = was_readonly;
    virObjectUnref(cfg);
    return ret;
}


4312
bool
4313
qemuDomainDiskSourceDiffers(virDomainDiskDefPtr disk,
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328
                            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;

4329 4330 4331 4332
    /* This won't be a network storage, so no need to get the diskPriv
     * in order to fetch the secret, thus NULL for param2 */
    if (qemuGetDriveSourceString(disk->src, NULL, &diskSrc) < 0 ||
        qemuGetDriveSourceString(origDisk->src, NULL, &origDiskSrc) < 0)
4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345
        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;
}


4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368
/*
 * 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);
4369 4370 4371 4372
    CHECK_EQ(bus, "bus", false);
    if (STRNEQ(disk->dst, orig_disk->dst)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("cannot modify field '%s' of the disk"),
4373
                       "target");
4374 4375 4376 4377
        return false;
    }
    CHECK_EQ(tray_status, "tray", true);
    CHECK_EQ(removable, "removable", true);
4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460

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

4461 4462 4463 4464 4465 4466 4467
    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);
4468
    /* "snapshot" is a libvirt internal field and thus can be changed */
4469
    /* startupPolicy is allowed to be updated. Therefore not checked here. */
4470
    CHECK_EQ(transient, "transient", true);
4471
    CHECK_EQ(info.bootIndex, "boot order", true);
4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483
    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;
    }
4484

4485 4486 4487 4488 4489 4490
    /* checks for fields stored in disk->src */
    /* unfortunately 'readonly' and 'shared' can't be converted to tristate
     * values thus we need to ignore the check if the new value is 'false' */
    CHECK_EQ(src->readonly, "readonly", true);
    CHECK_EQ(src->shared, "shared", true);

4491 4492 4493 4494 4495
#undef CHECK_EQ

    return true;
}

4496 4497 4498
bool
qemuDomainDiskBlockJobIsActive(virDomainDiskDefPtr disk)
{
4499 4500
    qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

4501 4502 4503 4504 4505 4506 4507 4508
    if (disk->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' already in active block job"),
                       disk->dst);

        return true;
    }

4509
    if (diskPriv->blockjob) {
4510 4511 4512 4513 4514 4515 4516 4517 4518 4519
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("disk '%s' already in active block job"),
                       disk->dst);
        return true;
    }

    return false;
}


4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
/**
 * 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++) {
4535 4536 4537 4538
        virDomainDiskDefPtr disk = vm->def->disks[i];
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

        if (!copy_only && diskPriv->blockjob)
4539 4540
            return true;

4541
        if (disk->mirror && disk->mirrorJob == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY)
4542 4543 4544 4545 4546 4547 4548
            return true;
    }

    return false;
}


4549 4550
int
qemuDomainUpdateDeviceList(virQEMUDriverPtr driver,
4551 4552
                           virDomainObjPtr vm,
                           int asyncJob)
4553 4554 4555
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char **aliases;
4556
    int rc;
4557 4558 4559 4560

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

4561 4562
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;
4563 4564 4565 4566
    rc = qemuMonitorGetDeviceAliases(priv->mon, &aliases);
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return -1;
    if (rc < 0)
4567 4568 4569 4570 4571 4572
        return -1;

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

4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622

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


4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638
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);

4639
 cleanup:
4640 4641 4642 4643
    virDomainDefFree(migratableDefSrc);
    virDomainDefFree(migratableDefDst);
    return ret;
}
4644 4645

bool
4646
qemuDomainAgentAvailable(virDomainObjPtr vm,
4647 4648
                         bool reportError)
{
4649 4650
    qemuDomainObjPrivatePtr priv = vm->privateData;

4651 4652 4653 4654 4655 4656 4657
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_RUNNING) {
        if (reportError) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain is not running"));
        }
        return false;
    }
4658 4659 4660 4661 4662 4663 4664 4665 4666
    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) {
4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678
        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;
4679 4680 4681 4682
        }
    }
    return true;
}
4683

4684

4685
static unsigned long long
4686
qemuDomainGetMemorySizeAlignment(virDomainDefPtr def)
4687
{
4688 4689 4690 4691 4692
    /* PPC requires the memory sizes to be rounded to 256MiB increments, so
     * round them to the size always. */
    if (ARCH_IS_PPC64(def->os.arch))
        return 256 * 1024;

4693 4694 4695 4696 4697 4698 4699
    /* Align memory size. QEMU requires rounding to next 4KiB block.
     * We'll take the "traditional" path and round it to 1MiB*/

    return 1024;
}


4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714
static unsigned long long
qemuDomainGetMemoryModuleSizeAlignment(const virDomainDef *def,
                                       const virDomainMemoryDef *mem ATTRIBUTE_UNUSED)
{
    /* PPC requires the memory sizes to be rounded to 256MiB increments, so
     * round them to the size always. */
    if (ARCH_IS_PPC64(def->os.arch))
        return 256 * 1024;

    /* dimm memory modules require 2MiB alignment rather than the 1MiB we are
     * using elsewhere. */
    return 2048;
}


4715 4716 4717
int
qemuDomainAlignMemorySizes(virDomainDefPtr def)
{
4718 4719
    unsigned long long maxmemkb = virMemoryMaxValue(false) >> 10;
    unsigned long long maxmemcapped = virMemoryMaxValue(true) >> 10;
4720
    unsigned long long initialmem = 0;
4721
    unsigned long long hotplugmem = 0;
4722
    unsigned long long mem;
4723
    unsigned long long align = qemuDomainGetMemorySizeAlignment(def);
4724 4725 4726 4727 4728
    size_t ncells = virDomainNumaGetNodeCount(def->numa);
    size_t i;

    /* align NUMA cell sizes if relevant */
    for (i = 0; i < ncells; i++) {
4729 4730
        mem = VIR_ROUND_UP(virDomainNumaGetNodeMemorySize(def->numa, i), align);
        initialmem += mem;
4731 4732 4733 4734 4735 4736 4737

        if (mem > maxmemkb) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("memory size of NUMA node '%zu' overflowed after "
                             "alignment"), i);
            return -1;
        }
4738
        virDomainNumaSetNodeMemorySize(def->numa, i, mem);
4739 4740
    }

4741 4742 4743 4744 4745
    /* align initial memory size, if NUMA is present calculate it as total of
     * individual aligned NUMA node sizes */
    if (initialmem == 0)
        initialmem = VIR_ROUND_UP(virDomainDefGetMemoryInitial(def), align);

4746 4747 4748 4749 4750 4751
    if (initialmem > maxmemcapped) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("initial memory size overflowed after alignment"));
        return -1;
    }

4752
    def->mem.max_memory = VIR_ROUND_UP(def->mem.max_memory, align);
4753 4754 4755 4756 4757
    if (def->mem.max_memory > maxmemkb) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("maximum memory size overflowed after alignment"));
        return -1;
    }
4758

4759
    /* Align memory module sizes */
4760 4761
    for (i = 0; i < def->nmems; i++) {
        align = qemuDomainGetMemoryModuleSizeAlignment(def, def->mems[i]);
4762
        def->mems[i]->size = VIR_ROUND_UP(def->mems[i]->size, align);
4763
        hotplugmem += def->mems[i]->size;
4764 4765 4766 4767 4768 4769 4770

        if (def->mems[i]->size > maxmemkb) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("size of memory module '%zu' overflowed after "
                             "alignment"), i);
            return -1;
        }
4771
    }
4772

4773 4774
    virDomainDefSetMemoryTotal(def, initialmem + hotplugmem);

4775 4776
    return 0;
}
4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787


/**
 * 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
4788 4789
qemuDomainMemoryDeviceAlignSize(virDomainDefPtr def,
                                virDomainMemoryDefPtr mem)
4790
{
4791
    mem->size = VIR_ROUND_UP(mem->size, qemuDomainGetMemorySizeAlignment(def));
4792
}
4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805


/**
 * qemuDomainGetMonitor:
 * @vm: domain object
 *
 * Returns the monitor pointer corresponding to the domain object @vm.
 */
qemuMonitorPtr
qemuDomainGetMonitor(virDomainObjPtr vm)
{
    return ((qemuDomainObjPrivatePtr) vm->privateData)->mon;
}
4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821


/**
 * 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;
4822 4823
    bool asynchronous = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_ASYNC);
    bool synchronous = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_SYNC);
4824

4825
    if (!synchronous && !asynchronous) {
4826 4827 4828 4829 4830 4831
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block jobs not supported with this QEMU binary"));
        return -1;
    }

    if (modern)
4832
        *modern = asynchronous;
4833 4834 4835

    return 0;
}
4836 4837 4838 4839 4840 4841 4842 4843 4844


/**
 * 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.
 */
4845
virDomainChrDefPtr
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855
qemuFindAgentConfig(virDomainDefPtr def)
{
    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;

4856 4857
        if (STREQ_NULLABLE(channel->target.name, "org.qemu.guest_agent.0"))
            return channel;
4858 4859
    }

4860
    return NULL;
4861
}
4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880


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"));
}
4881 4882


4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
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;
}


4901 4902 4903 4904 4905 4906
bool
qemuDomainMachineIsS390CCW(const virDomainDef *def)
{
    return STRPREFIX(def->os.machine, "s390-ccw");
}

4907

J
Ján Tomko 已提交
4908 4909 4910 4911 4912 4913 4914 4915
bool
qemuDomainMachineIsVirt(const virDomainDef *def)
{
    return STREQ(def->os.machine, "virt") ||
           STRPREFIX(def->os.machine, "virt-");
}


4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
static bool
qemuCheckMemoryDimmConflict(const virDomainDef *def,
                            const virDomainMemoryDef *mem)
{
    size_t i;

    for (i = 0; i < def->nmems; i++) {
         virDomainMemoryDefPtr tmp = def->mems[i];

         if (tmp == mem ||
             tmp->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM)
             continue;

         if (mem->info.addr.dimm.slot == tmp->info.addr.dimm.slot) {
             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("memory device slot '%u' is already being "
                              "used by another memory device"),
                            mem->info.addr.dimm.slot);
             return true;
         }

         if (mem->info.addr.dimm.base != 0 &&
             mem->info.addr.dimm.base == tmp->info.addr.dimm.base) {
             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("memory device base '0x%llx' is already being "
                              "used by another memory device"),
                            mem->info.addr.dimm.base);
             return true;
         }
    }

    return false;
}
static int
qemuDomainDefValidateMemoryHotplugDevice(const virDomainMemoryDef *mem,
                                         const virDomainDef *def)
{
    switch ((virDomainMemoryModel) mem->model) {
    case VIR_DOMAIN_MEMORY_MODEL_DIMM:
        if (mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM &&
            mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("only 'dimm' addresses are supported for the "
                             "pc-dimm device"));
            return -1;
        }

4963 4964 4965
        if (virDomainNumaGetNodeCount(def->numa) != 0) {
            if (mem->targetNode == -1) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
Y
Yuri Chornoivan 已提交
4966
                               _("target NUMA node needs to be specified for "
4967 4968 4969
                                 "memory device"));
                return -1;
            }
4970 4971
        }

4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
        if (mem->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM) {
            if (mem->info.addr.dimm.slot >= def->mem.memory_slots) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("memory device slot '%u' exceeds slots "
                                 "count '%u'"),
                               mem->info.addr.dimm.slot, def->mem.memory_slots);
                return -1;
            }


            if (qemuCheckMemoryDimmConflict(def, mem))
                return -1;
        }
        break;

    case VIR_DOMAIN_MEMORY_MODEL_NONE:
    case VIR_DOMAIN_MEMORY_MODEL_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid memory device type"));
        return -1;
    }

    return 0;
}


4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025
/**
 * qemuDomainDefValidateMemoryHotplug:
 * @def: domain definition
 * @qemuCaps: qemu capabilities object
 * @mem: definition of memory device that is to be added to @def with hotplug,
 *       NULL in case of regular VM startup
 *
 * Validates that the domain definition and memory modules have valid
 * configuration and are possibly able to accept @mem via hotplug if it's
 * non-NULL.
 *
 * Returns 0 on success; -1 and a libvirt error on error.
 */
int
qemuDomainDefValidateMemoryHotplug(const virDomainDef *def,
                                   virQEMUCapsPtr qemuCaps,
                                   const virDomainMemoryDef *mem)
{
    unsigned int nmems = def->nmems;
    unsigned long long hotplugSpace;
    unsigned long long hotplugMemory = 0;
    size_t i;

    hotplugSpace = def->mem.max_memory - virDomainDefGetMemoryInitial(def);

    if (mem) {
        nmems++;
        hotplugMemory = mem->size;
5026 5027 5028

        if (qemuDomainDefValidateMemoryHotplugDevice(mem, def) < 0)
            return -1;
5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047
    }

    if (!virDomainDefHasMemoryHotplug(def)) {
        if (nmems) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("cannot use/hotplug a memory device when domain "
                             "'maxMemory' is not defined"));
            return -1;
        }

        return 0;
    }

    if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PC_DIMM)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("memory hotplug isn't supported by this QEMU binary"));
        return -1;
    }

5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058
    if (!ARCH_IS_PPC64(def->os.arch)) {
        /* due to guest support, qemu would silently enable NUMA with one node
         * once the memory hotplug backend is enabled. To avoid possible
         * confusion we will enforce user originated numa configuration along
         * with memory hotplug. */
        if (virDomainNumaGetNodeCount(def->numa) == 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("At least one numa node has to be configured when "
                             "enabling memory hotplug"));
            return -1;
        }
5059 5060 5061 5062 5063 5064 5065 5066 5067
    }

    if (nmems > def->mem.memory_slots) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("memory device count '%u' exceeds slots count '%u'"),
                       nmems, def->mem.memory_slots);
        return -1;
    }

5068
    for (i = 0; i < def->nmems; i++) {
5069 5070
        hotplugMemory += def->mems[i]->size;

5071 5072 5073 5074 5075 5076
        /* already existing devices don't need to be checked on hotplug */
        if (!mem &&
            qemuDomainDefValidateMemoryHotplugDevice(def->mems[i], def) < 0)
            return -1;
    }

5077 5078 5079 5080 5081 5082 5083 5084 5085 5086
    if (hotplugMemory > hotplugSpace) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("memory device total size exceeds hotplug space"));
        return -1;
    }

    return 0;
}


5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
bool
qemuDomainMachineHasBuiltinIDE(const virDomainDef *def)
{
    return qemuDomainMachineIsI440FX(def) ||
        STREQ(def->os.machine, "malta") ||
        STREQ(def->os.machine, "sun4u") ||
        STREQ(def->os.machine, "g3beige");
}


5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120
/**
 * 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 */
5121
    if (!virDomainDefHasMemballoon(vm->def)) {
5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
        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;

5155 5156
        vm->def->mem.cur_balloon = balloon;
    }
5157 5158 5159

    return 0;
}
5160 5161 5162


/**
5163
 * qemuDomainGetMemLockLimitBytes:
5164 5165 5166 5167
 *
 * @def: domain definition
 *
 * Returns the size of the memory in bytes that needs to be set as
5168
 * RLIMIT_MEMLOCK for the QEMU process.
5169 5170 5171 5172
 * If a mem.hard_limit is set, then that value is preferred; otherwise, the
 * value returned may depend upon the architecture or devices present.
 */
unsigned long long
5173
qemuDomainGetMemLockLimitBytes(virDomainDefPtr def)
5174 5175 5176
{
    unsigned long long memKB;

5177 5178 5179 5180 5181 5182
    /* prefer the hard limit */
    if (virMemoryLimitIsSet(def->mem.hard_limit)) {
        memKB = def->mem.hard_limit;
        goto done;
    }

5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260
    if (ARCH_IS_PPC64(def->os.arch)) {
        unsigned long long maxMemory;
        unsigned long long memory;
        unsigned long long baseLimit;
        unsigned long long passthroughLimit;
        size_t nPCIHostBridges;
        size_t i;
        bool usesVFIO = false;

        /* TODO: Detect at runtime once we start using more than just
         *       the default PCI Host Bridge */
        nPCIHostBridges = 1;

        for (i = 0; i < def->nhostdevs; i++) {
            virDomainHostdevDefPtr dev = def->hostdevs[i];

            if (dev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
                dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
                dev->source.subsys.u.pci.backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
                usesVFIO = true;
                break;
            }
        }

        memory = virDomainDefGetMemoryActual(def);

        if (def->mem.max_memory)
            maxMemory = def->mem.max_memory;
        else
            maxMemory = memory;

        /* baseLimit := maxMemory / 128                                  (a)
         *              + 4 MiB * #PHBs + 8 MiB                          (b)
         *
         * (a) is the hash table
         *
         * (b) is accounting for the 32-bit DMA window - it could be either the
         * KVM accelerated TCE tables for emulated devices, or the VFIO
         * userspace view. The 4 MiB per-PHB (including the default one) covers
         * a 2GiB DMA window: default is 1GiB, but it's possible it'll be
         * increased to help performance. The 8 MiB extra should be plenty for
         * the TCE table index for any reasonable number of PHBs and several
         * spapr-vlan or spapr-vscsi devices (512kB + a tiny bit each) */
        baseLimit = maxMemory / 128 +
                    4096 * nPCIHostBridges +
                    8192;

        /* passthroughLimit := max( 2 GiB * #PHBs,                       (c)
         *                          memory                               (d)
         *                          + memory * 1/512 * #PHBs + 8 MiB )   (e)
         *
         * (c) is the pre-DDW VFIO DMA window accounting. We're allowing 2 GiB
         * rather than 1 GiB
         *
         * (d) is the with-DDW (and memory pre-registration and related
         * features) DMA window accounting - assuming that we only account RAM
         * once, even if mapped to multiple PHBs
         *
         * (e) is the with-DDW userspace view and overhead for the 64-bit DMA
         * window. This is based a bit on expected guest behaviour, but there
         * really isn't a way to completely avoid that. We assume the guest
         * requests a 64-bit DMA window (per PHB) just big enough to map all
         * its RAM. 4 kiB page size gives the 1/512; it will be less with 64
         * kiB pages, less still if the guest is mapped with hugepages (unlike
         * the default 32-bit DMA window, DDW windows can use large IOMMU
         * pages). 8 MiB is for second and further level overheads, like (b) */
        passthroughLimit = MAX(2 * 1024 * 1024 * nPCIHostBridges,
                               memory +
                               memory / 512 * nPCIHostBridges + 8192);

        if (usesVFIO)
            memKB = baseLimit + passthroughLimit;
        else
            memKB = baseLimit;

        goto done;
    }

5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278
    /* For device passthrough using VFIO the guest memory and MMIO memory
     * regions need to be locked persistent in order to allow DMA.
     *
     * Currently the below limit is based on assumptions about the x86 platform.
     *
     * The chosen value of 1GiB below originates from x86 systems where it was
     * used as space reserved for the MMIO region for the whole system.
     *
     * On x86_64 systems the MMIO regions of the IOMMU mapped devices don't
     * count towards the locked memory limit since the memory is owned by the
     * device. Emulated devices though do count, but the regions are usually
     * small. Although it's not guaranteed that the limit will be enough for all
     * configurations it didn't pose a problem for now.
     *
     * http://www.redhat.com/archives/libvir-list/2015-November/msg00329.html
     *
     * Note that this may not be valid for all platforms.
     */
5279
    memKB = virDomainDefGetMemoryActual(def) + 1024 * 1024;
5280

5281
 done:
5282 5283
    return memKB << 10;
}
5284 5285 5286 5287 5288


/**
 * @def: domain definition
 *
5289 5290 5291
 * Returns true if the locked memory limit needs to be set or updated because
 * of domain configuration, VFIO passthrough devices or architecture-specific
 * requirements.
5292 5293
 * */
bool
5294
qemuDomainRequiresMemLock(virDomainDefPtr def)
5295 5296 5297 5298 5299 5300
{
    size_t i;

    if (def->mem.locked)
        return true;

5301 5302 5303 5304
    /* ppc64 domains need to lock some memory even when VFIO is not used */
    if (ARCH_IS_PPC64(def->os.arch))
        return true;

5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315
    for (i = 0; i < def->nhostdevs; i++) {
        virDomainHostdevDefPtr dev = def->hostdevs[i];

        if (dev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
            dev->source.subsys.u.pci.backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
            return true;
    }

    return false;
}
5316

5317 5318 5319 5320 5321 5322 5323
/**
 * qemuDomainAdjustMaxMemLock:
 * @vm: domain
 *
 * Adjust the memory locking limit for the QEMU process associated to @vm, in
 * order to comply with VFIO or architecture requirements.
 *
5324 5325 5326 5327
 * The limit will not be changed unless doing so is needed; the first time
 * the limit is changed, the original (default) limit is stored in @vm and
 * that value will be restored if qemuDomainAdjustMaxMemLock() is called once
 * memory locking is no longer required.
5328 5329 5330 5331 5332 5333 5334 5335 5336
 *
 * Returns: 0 on success, <0 on failure
 */
int
qemuDomainAdjustMaxMemLock(virDomainObjPtr vm)
{
    unsigned long long bytes = 0;
    int ret = -1;

5337
    if (qemuDomainRequiresMemLock(vm->def)) {
5338 5339 5340 5341 5342 5343 5344 5345
        /* If this is the first time adjusting the limit, save the current
         * value so that we can restore it once memory locking is no longer
         * required. Failing to obtain the current limit is not a critical
         * failure, it just means we'll be unable to lower it later */
        if (!vm->original_memlock) {
            if (virProcessGetMaxMemLock(vm->pid, &(vm->original_memlock)) < 0)
                vm->original_memlock = 0;
        }
5346
        bytes = qemuDomainGetMemLockLimitBytes(vm->def);
5347 5348 5349 5350 5351 5352
    } else {
        /* Once memory locking is no longer required, we can restore the
         * original, usually very low, limit */
        bytes = vm->original_memlock;
        vm->original_memlock = 0;
    }
5353 5354 5355 5356 5357 5358 5359 5360 5361 5362

    /* Trying to set the memory locking limit to zero is a no-op */
    if (virProcessSetMaxMemLock(vm->pid, bytes) < 0)
        goto out;

    ret = 0;

 out:
     return ret;
}
5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376

/**
 * qemuDomainHasVcpuPids:
 * @vm: Domain object
 *
 * Returns true if we were able to successfully detect vCPU pids for the VM.
 */
bool
qemuDomainHasVcpuPids(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    return priv->nvcpupids > 0;
}
5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396


/**
 * qemuDomainGetVcpuPid:
 * @vm: domain object
 * @vcpu: cpu id
 *
 * Returns the vCPU pid. If @vcpu is offline or out of range 0 is returned.
 */
pid_t
qemuDomainGetVcpuPid(virDomainObjPtr vm,
                     unsigned int vcpu)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (vcpu >= priv->nvcpupids)
        return 0;

    return priv->vcpupids[vcpu];
}
5397 5398 5399 5400 5401 5402 5403 5404 5405 5406


/**
 * qemuDomainDetectVcpuPids:
 * @driver: qemu driver data
 * @vm: domain object
 * @asyncJob: current asynchronous job type
 *
 * Updates vCPU thread ids in the private data of @vm.
 *
5407
 * Returns number of detected vCPU threads on success, -1 on error and reports
5408
 * an appropriate error, -2 if the domain doesn't exist any more.
5409 5410 5411 5412 5413 5414 5415
 */
int
qemuDomainDetectVcpuPids(virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         int asyncJob)
{
    pid_t *cpupids = NULL;
5416
    int ncpupids = 0;
5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446
    qemuDomainObjPrivatePtr priv = vm->privateData;

    /*
     * Current QEMU *can* report info about host threads mapped
     * to vCPUs, but it is not in a manner we can correctly
     * deal with. The TCG CPU emulation does have a separate vCPU
     * thread, but it runs every vCPU in that same thread. So it
     * is impossible to setup different affinity per thread.
     *
     * What's more the 'query-cpus' command returns bizarre
     * data for the threads. It gives the TCG thread for the
     * vCPU 0, but for vCPUs 1-> N, it actually replies with
     * the main process thread ID.
     *
     * The result is that when we try to set affinity for
     * vCPU 1, it will actually change the affinity of the
     * emulator thread :-( When you try to set affinity for
     * vCPUs 2, 3.... it will fail if the affinity was
     * different from vCPU 1.
     *
     * We *could* allow vcpu pinning with TCG, if we made the
     * restriction that all vCPUs had the same mask. This would
     * at least let us separate emulator from vCPUs threads, as
     * we do for KVM. It would need some changes to our cgroups
     * CPU layout though, and error reporting for the config
     * restrictions.
     *
     * Just disable CPU pinning with TCG until someone wants
     * to try to do this hard work.
     */
5447 5448
    if (vm->def->virtType == VIR_DOMAIN_VIRT_QEMU)
        goto done;
5449 5450 5451 5452

    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;
    ncpupids = qemuMonitorGetCPUInfo(priv->mon, &cpupids);
5453 5454
    if (qemuDomainObjExitMonitor(driver, vm) < 0) {
        VIR_FREE(cpupids);
5455
        return -2;
5456 5457
    }
    /* failure to get the VCPU <-> PID mapping or to execute the query
5458 5459 5460 5461
     * command will not be treated fatal as some versions of qemu don't
     * support this command */
    if (ncpupids <= 0) {
        virResetLastError();
5462 5463
        ncpupids = 0;
        goto done;
5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474
    }

    if (ncpupids != virDomainDefGetVcpus(vm->def)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("got wrong number of vCPU pids from QEMU monitor. "
                         "got %d, wanted %d"),
                       ncpupids, virDomainDefGetVcpus(vm->def));
        VIR_FREE(cpupids);
        return -1;
    }

5475 5476
 done:
    VIR_FREE(priv->vcpupids);
5477 5478
    priv->nvcpupids = ncpupids;
    priv->vcpupids = cpupids;
5479
    return ncpupids;
5480
}
5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501


bool
qemuDomainSupportsNicdev(virDomainDefPtr def,
                         virDomainNetDefPtr net)
{
    /* non-virtio ARM nics require legacy -net nic */
    if (((def->os.arch == VIR_ARCH_ARMV7L) ||
        (def->os.arch == VIR_ARCH_AARCH64)) &&
        net->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
        net->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
        return false;

    return true;
}

bool
qemuDomainSupportsNetdev(virDomainDefPtr def,
                         virQEMUCapsPtr qemuCaps,
                         virDomainNetDefPtr net)
{
5502
    if (!qemuDomainSupportsNicdev(def, net))
5503 5504 5505
        return false;
    return virQEMUCapsGet(qemuCaps, QEMU_CAPS_NETDEV);
}
J
John Ferlan 已提交
5506 5507 5508 5509 5510 5511 5512


int
qemuDomainNetVLAN(virDomainNetDefPtr def)
{
    return qemuDomainDeviceAliasIndex(&def->info, "net");
}
P
Peter Krempa 已提交
5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528


virDomainDiskDefPtr
qemuDomainDiskByName(virDomainDefPtr def,
                     const char *name)
{
    virDomainDiskDefPtr ret;

    if (!(ret = virDomainDiskByName(def, name, true))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("No device found for specified path"));
        return NULL;
    }

    return ret;
}
5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559


/**
 * qemuDomainDefValidateDiskLunSource:
 * @src: disk source struct
 *
 * Validate whether the disk source is valid for disk device='lun'.
 *
 * Returns 0 if the configuration is valid -1 and a libvirt error if the soure
 * is invalid.
 */
int
qemuDomainDefValidateDiskLunSource(const virStorageSource *src)
{
    if (virStorageSourceGetActualType(src) == VIR_STORAGE_TYPE_NETWORK) {
        if (src->protocol != VIR_STORAGE_NET_PROTOCOL_ISCSI) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device='lun' is not supported "
                             "for protocol='%s'"),
                           virStorageNetProtocolTypeToString(src->protocol));
            return -1;
        }
    } else if (!virStorageSourceIsBlockLocal(src)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk device='lun' is only valid for block "
                         "type disk source"));
        return -1;
    }

    return 0;
}
5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579


int
qemuDomainPrepareChannel(virDomainChrDefPtr channel,
                         const char *domainChannelTargetDir)
{
    if (channel->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO &&
        channel->source.type == VIR_DOMAIN_CHR_TYPE_UNIX &&
        !channel->source.data.nix.path) {
        if (virAsprintf(&channel->source.data.nix.path,
                        "%s/%s", domainChannelTargetDir,
                        channel->target.name ? channel->target.name
                        : "unknown.sock") < 0)
            return -1;

        channel->source.data.nix.listen = true;
    }

    return 0;
}