fixup! to ? - more compiler fixes
[libvirt/ericb.git] / src / qemu / qemu_domain.c
blobd8b3fb182f2cfafc445d97ceebd377f825b3b9a8
1 /*
2 * qemu_domain.c: QEMU domain private state
4 * Copyright (C) 2006-2019 Red Hat, Inc.
5 * Copyright (C) 2006 Daniel P. Berrange
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library. If not, see
19 * <http://www.gnu.org/licenses/>.
22 #include <config.h>
24 #include "qemu_domain.h"
25 #include "qemu_alias.h"
26 #include "qemu_block.h"
27 #include "qemu_cgroup.h"
28 #include "qemu_command.h"
29 #include "qemu_process.h"
30 #include "qemu_parse_command.h"
31 #include "qemu_capabilities.h"
32 #include "qemu_migration.h"
33 #include "qemu_migration_params.h"
34 #include "qemu_security.h"
35 #include "qemu_extdevice.h"
36 #include "viralloc.h"
37 #include "virlog.h"
38 #include "virerror.h"
39 #include "c-ctype.h"
40 #include "cpu/cpu.h"
41 #include "viruuid.h"
42 #include "virfile.h"
43 #include "domain_addr.h"
44 #include "domain_event.h"
45 #include "virtime.h"
46 #include "virnetdevopenvswitch.h"
47 #include "virstoragefile.h"
48 #include "virstring.h"
49 #include "virthreadjob.h"
50 #include "viratomic.h"
51 #include "virprocess.h"
52 #include "vircrypto.h"
53 #include "virrandom.h"
54 #include "virsystemd.h"
55 #include "secret_util.h"
56 #include "logging/log_manager.h"
57 #include "locking/domain_lock.h"
58 #include "virdomainsnapshotobjlist.h"
59 #include "virdomaincheckpointobjlist.h"
60 #include "backup_conf.h"
62 #ifdef MAJOR_IN_MKDEV
63 # include <sys/mkdev.h>
64 #elif MAJOR_IN_SYSMACROS
65 # include <sys/sysmacros.h>
66 #endif
67 #include <sys/time.h>
68 #include <fcntl.h>
69 #if defined(HAVE_SYS_MOUNT_H)
70 # include <sys/mount.h>
71 #endif
72 #ifdef WITH_SELINUX
73 # include <selinux/selinux.h>
74 #endif
76 #include <libxml/xpathInternals.h>
77 #include "dosname.h"
79 #define VIR_FROM_THIS VIR_FROM_QEMU
81 VIR_LOG_INIT("qemu.qemu_domain");
83 #define QEMU_NAMESPACE_HREF "http://libvirt.org/schemas/domain/qemu/1.0"
85 VIR_ENUM_IMPL(qemuDomainJob, QEMU_JOB_LAST,
86 "none",
87 "query",
88 "destroy",
89 "suspend",
90 "modify",
91 "abort",
92 "migration operation",
93 "none", /* async job is never stored in job.active */
94 "async nested",
97 VIR_ENUM_IMPL(qemuDomainAgentJob, QEMU_AGENT_JOB_LAST,
98 "none",
99 "query",
100 "modify",
103 VIR_ENUM_IMPL(qemuDomainAsyncJob, QEMU_ASYNC_JOB_LAST,
104 "none",
105 "migration out",
106 "migration in",
107 "save",
108 "dump",
109 "snapshot",
110 "start",
113 VIR_ENUM_IMPL(qemuDomainNamespace, QEMU_DOMAIN_NS_LAST,
114 "mount",
118 #define PROC_MOUNTS "/proc/mounts"
119 #define DEVPREFIX "/dev/"
120 #define DEV_VFIO "/dev/vfio/vfio"
121 #define DEVICE_MAPPER_CONTROL_PATH "/dev/mapper/control"
122 #define DEV_SEV "/dev/sev"
125 struct _qemuDomainLogContext {
126 virObject parent;
128 int writefd;
129 int readfd; /* Only used if manager == NULL */
130 off_t pos;
131 ino_t inode; /* Only used if manager != NULL */
132 char *path;
133 virLogManagerPtr manager;
136 static virClassPtr qemuDomainLogContextClass;
137 static virClassPtr qemuDomainSaveCookieClass;
139 static void qemuDomainLogContextDispose(void *obj);
140 static void qemuDomainSaveCookieDispose(void *obj);
143 static int
144 qemuDomainPrepareStorageSourceBlockdev(virDomainDiskDefPtr disk,
145 virStorageSourcePtr src,
146 qemuDomainObjPrivatePtr priv,
147 virQEMUDriverConfigPtr cfg);
150 static int
151 qemuDomainOnceInit(void)
153 if (!VIR_CLASS_NEW(qemuDomainLogContext, virClassForObject()))
154 return -1;
156 if (!VIR_CLASS_NEW(qemuDomainSaveCookie, virClassForObject()))
157 return -1;
159 return 0;
162 VIR_ONCE_GLOBAL_INIT(qemuDomain);
164 static void
165 qemuDomainLogContextDispose(void *obj)
167 qemuDomainLogContextPtr ctxt = obj;
168 VIR_DEBUG("ctxt=%p", ctxt);
170 virLogManagerFree(ctxt->manager);
171 VIR_FREE(ctxt->path);
172 VIR_FORCE_CLOSE(ctxt->writefd);
173 VIR_FORCE_CLOSE(ctxt->readfd);
176 const char *
177 qemuDomainAsyncJobPhaseToString(qemuDomainAsyncJob job,
178 int phase ATTRIBUTE_UNUSED)
180 switch (job) {
181 case QEMU_ASYNC_JOB_MIGRATION_OUT:
182 case QEMU_ASYNC_JOB_MIGRATION_IN:
183 return qemuMigrationJobPhaseTypeToString(phase);
185 case QEMU_ASYNC_JOB_SAVE:
186 case QEMU_ASYNC_JOB_DUMP:
187 case QEMU_ASYNC_JOB_SNAPSHOT:
188 case QEMU_ASYNC_JOB_START:
189 case QEMU_ASYNC_JOB_NONE:
190 ATTRIBUTE_FALLTHROUGH;
191 case QEMU_ASYNC_JOB_LAST:
192 break;
195 return "none";
199 qemuDomainAsyncJobPhaseFromString(qemuDomainAsyncJob job,
200 const char *phase)
202 if (!phase)
203 return 0;
205 switch (job) {
206 case QEMU_ASYNC_JOB_MIGRATION_OUT:
207 case QEMU_ASYNC_JOB_MIGRATION_IN:
208 return qemuMigrationJobPhaseTypeFromString(phase);
210 case QEMU_ASYNC_JOB_SAVE:
211 case QEMU_ASYNC_JOB_DUMP:
212 case QEMU_ASYNC_JOB_SNAPSHOT:
213 case QEMU_ASYNC_JOB_START:
214 case QEMU_ASYNC_JOB_NONE:
215 ATTRIBUTE_FALLTHROUGH;
216 case QEMU_ASYNC_JOB_LAST:
217 break;
220 if (STREQ(phase, "none"))
221 return 0;
222 else
223 return -1;
227 bool
228 qemuDomainNamespaceEnabled(virDomainObjPtr vm,
229 qemuDomainNamespace ns)
231 qemuDomainObjPrivatePtr priv = vm->privateData;
233 return priv->namespaces &&
234 virBitmapIsBitSet(priv->namespaces, ns);
238 static int
239 qemuDomainEnableNamespace(virDomainObjPtr vm,
240 qemuDomainNamespace ns)
242 qemuDomainObjPrivatePtr priv = vm->privateData;
244 if (!priv->namespaces &&
245 !(priv->namespaces = virBitmapNew(QEMU_DOMAIN_NS_LAST)))
246 return -1;
248 if (virBitmapSetBit(priv->namespaces, ns) < 0) {
249 virReportError(VIR_ERR_INTERNAL_ERROR,
250 _("Unable to enable namespace: %s"),
251 qemuDomainNamespaceTypeToString(ns));
252 return -1;
255 return 0;
259 static void
260 qemuDomainDisableNamespace(virDomainObjPtr vm,
261 qemuDomainNamespace ns)
263 qemuDomainObjPrivatePtr priv = vm->privateData;
265 if (priv->namespaces) {
266 ignore_value(virBitmapClearBit(priv->namespaces, ns));
267 if (virBitmapIsAllClear(priv->namespaces)) {
268 virBitmapFree(priv->namespaces);
269 priv->namespaces = NULL;
275 void
276 qemuDomainEventEmitJobCompleted(virQEMUDriverPtr driver,
277 virDomainObjPtr vm)
279 qemuDomainObjPrivatePtr priv = vm->privateData;
280 virObjectEventPtr event;
281 virTypedParameterPtr params = NULL;
282 int nparams = 0;
283 int type;
285 if (!priv->job.completed)
286 return;
288 if (qemuDomainJobInfoToParams(priv->job.completed, &type,
289 &params, &nparams) < 0) {
290 VIR_WARN("Could not get stats for completed job; domain %s",
291 vm->def->name);
294 event = virDomainEventJobCompletedNewFromObj(vm, params, nparams);
295 virObjectEventStateQueue(driver->domainEventState, event);
299 static int
300 qemuDomainObjInitJob(qemuDomainObjPrivatePtr priv)
302 memset(&priv->job, 0, sizeof(priv->job));
304 if (virCondInit(&priv->job.cond) < 0)
305 return -1;
307 if (virCondInit(&priv->job.asyncCond) < 0) {
308 virCondDestroy(&priv->job.cond);
309 return -1;
312 return 0;
315 static void
316 qemuDomainObjResetJob(qemuDomainObjPrivatePtr priv)
318 qemuDomainJobObjPtr job = &priv->job;
320 job->active = QEMU_JOB_NONE;
321 job->owner = 0;
322 job->ownerAPI = NULL;
323 job->started = 0;
327 static void
328 qemuDomainObjResetAgentJob(qemuDomainObjPrivatePtr priv)
330 qemuDomainJobObjPtr job = &priv->job;
332 job->agentActive = QEMU_AGENT_JOB_NONE;
333 job->agentOwner = 0;
334 job->agentOwnerAPI = NULL;
335 job->agentStarted = 0;
339 static void
340 qemuDomainObjResetAsyncJob(qemuDomainObjPrivatePtr priv)
342 qemuDomainJobObjPtr job = &priv->job;
344 job->asyncJob = QEMU_ASYNC_JOB_NONE;
345 job->asyncOwner = 0;
346 job->asyncOwnerAPI = NULL;
347 job->asyncStarted = 0;
348 job->phase = 0;
349 job->mask = QEMU_JOB_DEFAULT_MASK;
350 job->abortJob = false;
351 job->spiceMigration = false;
352 job->spiceMigrated = false;
353 job->dumpCompleted = false;
354 VIR_FREE(job->error);
355 VIR_FREE(job->current);
356 qemuMigrationParamsFree(job->migParams);
357 job->migParams = NULL;
358 job->apiFlags = 0;
361 void
362 qemuDomainObjRestoreJob(virDomainObjPtr obj,
363 qemuDomainJobObjPtr job)
365 qemuDomainObjPrivatePtr priv = obj->privateData;
367 memset(job, 0, sizeof(*job));
368 job->active = priv->job.active;
369 job->owner = priv->job.owner;
370 job->asyncJob = priv->job.asyncJob;
371 job->asyncOwner = priv->job.asyncOwner;
372 job->phase = priv->job.phase;
373 VIR_STEAL_PTR(job->migParams, priv->job.migParams);
374 job->apiFlags = priv->job.apiFlags;
376 qemuDomainObjResetJob(priv);
377 qemuDomainObjResetAsyncJob(priv);
380 static void
381 qemuDomainObjFreeJob(qemuDomainObjPrivatePtr priv)
383 VIR_FREE(priv->job.current);
384 VIR_FREE(priv->job.completed);
385 virCondDestroy(&priv->job.cond);
386 virCondDestroy(&priv->job.asyncCond);
389 static bool
390 qemuDomainTrackJob(qemuDomainJob job)
392 return (QEMU_DOMAIN_TRACK_JOBS & JOB_MASK(job)) != 0;
397 qemuDomainJobInfoUpdateTime(qemuDomainJobInfoPtr jobInfo)
399 unsigned long long now;
401 if (!jobInfo->started)
402 return 0;
404 if (virTimeMillisNow(&now) < 0)
405 return -1;
407 if (now < jobInfo->started) {
408 VIR_WARN("Async job starts in the future");
409 jobInfo->started = 0;
410 return 0;
413 jobInfo->timeElapsed = now - jobInfo->started;
414 return 0;
418 qemuDomainJobInfoUpdateDowntime(qemuDomainJobInfoPtr jobInfo)
420 unsigned long long now;
422 if (!jobInfo->stopped)
423 return 0;
425 if (virTimeMillisNow(&now) < 0)
426 return -1;
428 if (now < jobInfo->stopped) {
429 VIR_WARN("Guest's CPUs stopped in the future");
430 jobInfo->stopped = 0;
431 return 0;
434 jobInfo->stats.mig.downtime = now - jobInfo->stopped;
435 jobInfo->stats.mig.downtime_set = true;
436 return 0;
439 static virDomainJobType
440 qemuDomainJobStatusToType(qemuDomainJobStatus status)
442 switch (status) {
443 case QEMU_DOMAIN_JOB_STATUS_NONE:
444 break;
446 case QEMU_DOMAIN_JOB_STATUS_ACTIVE:
447 case QEMU_DOMAIN_JOB_STATUS_MIGRATING:
448 case QEMU_DOMAIN_JOB_STATUS_QEMU_COMPLETED:
449 case QEMU_DOMAIN_JOB_STATUS_POSTCOPY:
450 case QEMU_DOMAIN_JOB_STATUS_PAUSED:
451 return VIR_DOMAIN_JOB_UNBOUNDED;
453 case QEMU_DOMAIN_JOB_STATUS_COMPLETED:
454 return VIR_DOMAIN_JOB_COMPLETED;
456 case QEMU_DOMAIN_JOB_STATUS_FAILED:
457 return VIR_DOMAIN_JOB_FAILED;
459 case QEMU_DOMAIN_JOB_STATUS_CANCELED:
460 return VIR_DOMAIN_JOB_CANCELLED;
463 return VIR_DOMAIN_JOB_NONE;
467 qemuDomainJobInfoToInfo(qemuDomainJobInfoPtr jobInfo,
468 virDomainJobInfoPtr info)
470 info->type = qemuDomainJobStatusToType(jobInfo->status);
471 info->timeElapsed = jobInfo->timeElapsed;
473 switch (jobInfo->statsType) {
474 case QEMU_DOMAIN_JOB_STATS_TYPE_MIGRATION:
475 info->memTotal = jobInfo->stats.mig.ram_total;
476 info->memRemaining = jobInfo->stats.mig.ram_remaining;
477 info->memProcessed = jobInfo->stats.mig.ram_transferred;
478 info->fileTotal = jobInfo->stats.mig.disk_total +
479 jobInfo->mirrorStats.total;
480 info->fileRemaining = jobInfo->stats.mig.disk_remaining +
481 (jobInfo->mirrorStats.total -
482 jobInfo->mirrorStats.transferred);
483 info->fileProcessed = jobInfo->stats.mig.disk_transferred +
484 jobInfo->mirrorStats.transferred;
485 break;
487 case QEMU_DOMAIN_JOB_STATS_TYPE_SAVEDUMP:
488 info->memTotal = jobInfo->stats.mig.ram_total;
489 info->memRemaining = jobInfo->stats.mig.ram_remaining;
490 info->memProcessed = jobInfo->stats.mig.ram_transferred;
491 break;
493 case QEMU_DOMAIN_JOB_STATS_TYPE_MEMDUMP:
494 info->memTotal = jobInfo->stats.dump.total;
495 info->memProcessed = jobInfo->stats.dump.completed;
496 info->memRemaining = info->memTotal - info->memProcessed;
497 break;
499 case QEMU_DOMAIN_JOB_STATS_TYPE_NONE:
500 break;
503 info->dataTotal = info->memTotal + info->fileTotal;
504 info->dataRemaining = info->memRemaining + info->fileRemaining;
505 info->dataProcessed = info->memProcessed + info->fileProcessed;
507 return 0;
511 static int
512 qemuDomainMigrationJobInfoToParams(qemuDomainJobInfoPtr jobInfo,
513 int *type,
514 virTypedParameterPtr *params,
515 int *nparams)
517 qemuMonitorMigrationStats *stats = &jobInfo->stats.mig;
518 qemuDomainMirrorStatsPtr mirrorStats = &jobInfo->mirrorStats;
519 virTypedParameterPtr par = NULL;
520 int maxpar = 0;
521 int npar = 0;
522 unsigned long long mirrorRemaining = mirrorStats->total -
523 mirrorStats->transferred;
525 if (virTypedParamsAddInt(&par, &npar, &maxpar,
526 VIR_DOMAIN_JOB_OPERATION,
527 jobInfo->operation) < 0)
528 goto error;
530 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
531 VIR_DOMAIN_JOB_TIME_ELAPSED,
532 jobInfo->timeElapsed) < 0)
533 goto error;
535 if (jobInfo->timeDeltaSet &&
536 jobInfo->timeElapsed > jobInfo->timeDelta &&
537 virTypedParamsAddULLong(&par, &npar, &maxpar,
538 VIR_DOMAIN_JOB_TIME_ELAPSED_NET,
539 jobInfo->timeElapsed - jobInfo->timeDelta) < 0)
540 goto error;
542 if (stats->downtime_set &&
543 virTypedParamsAddULLong(&par, &npar, &maxpar,
544 VIR_DOMAIN_JOB_DOWNTIME,
545 stats->downtime) < 0)
546 goto error;
548 if (stats->downtime_set &&
549 jobInfo->timeDeltaSet &&
550 stats->downtime > jobInfo->timeDelta &&
551 virTypedParamsAddULLong(&par, &npar, &maxpar,
552 VIR_DOMAIN_JOB_DOWNTIME_NET,
553 stats->downtime - jobInfo->timeDelta) < 0)
554 goto error;
556 if (stats->setup_time_set &&
557 virTypedParamsAddULLong(&par, &npar, &maxpar,
558 VIR_DOMAIN_JOB_SETUP_TIME,
559 stats->setup_time) < 0)
560 goto error;
562 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
563 VIR_DOMAIN_JOB_DATA_TOTAL,
564 stats->ram_total +
565 stats->disk_total +
566 mirrorStats->total) < 0 ||
567 virTypedParamsAddULLong(&par, &npar, &maxpar,
568 VIR_DOMAIN_JOB_DATA_PROCESSED,
569 stats->ram_transferred +
570 stats->disk_transferred +
571 mirrorStats->transferred) < 0 ||
572 virTypedParamsAddULLong(&par, &npar, &maxpar,
573 VIR_DOMAIN_JOB_DATA_REMAINING,
574 stats->ram_remaining +
575 stats->disk_remaining +
576 mirrorRemaining) < 0)
577 goto error;
579 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
580 VIR_DOMAIN_JOB_MEMORY_TOTAL,
581 stats->ram_total) < 0 ||
582 virTypedParamsAddULLong(&par, &npar, &maxpar,
583 VIR_DOMAIN_JOB_MEMORY_PROCESSED,
584 stats->ram_transferred) < 0 ||
585 virTypedParamsAddULLong(&par, &npar, &maxpar,
586 VIR_DOMAIN_JOB_MEMORY_REMAINING,
587 stats->ram_remaining) < 0)
588 goto error;
590 if (stats->ram_bps &&
591 virTypedParamsAddULLong(&par, &npar, &maxpar,
592 VIR_DOMAIN_JOB_MEMORY_BPS,
593 stats->ram_bps) < 0)
594 goto error;
596 if (stats->ram_duplicate_set) {
597 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
598 VIR_DOMAIN_JOB_MEMORY_CONSTANT,
599 stats->ram_duplicate) < 0 ||
600 virTypedParamsAddULLong(&par, &npar, &maxpar,
601 VIR_DOMAIN_JOB_MEMORY_NORMAL,
602 stats->ram_normal) < 0 ||
603 virTypedParamsAddULLong(&par, &npar, &maxpar,
604 VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES,
605 stats->ram_normal_bytes) < 0)
606 goto error;
609 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
610 VIR_DOMAIN_JOB_MEMORY_DIRTY_RATE,
611 stats->ram_dirty_rate) < 0 ||
612 virTypedParamsAddULLong(&par, &npar, &maxpar,
613 VIR_DOMAIN_JOB_MEMORY_ITERATION,
614 stats->ram_iteration) < 0 ||
615 virTypedParamsAddULLong(&par, &npar, &maxpar,
616 VIR_DOMAIN_JOB_MEMORY_POSTCOPY_REQS,
617 stats->ram_postcopy_reqs) < 0)
618 goto error;
620 if (stats->ram_page_size > 0 &&
621 virTypedParamsAddULLong(&par, &npar, &maxpar,
622 VIR_DOMAIN_JOB_MEMORY_PAGE_SIZE,
623 stats->ram_page_size) < 0)
624 goto error;
626 /* The remaining stats are disk, mirror, or migration specific
627 * so if this is a SAVEDUMP, we can just skip them */
628 if (jobInfo->statsType == QEMU_DOMAIN_JOB_STATS_TYPE_SAVEDUMP)
629 goto done;
631 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
632 VIR_DOMAIN_JOB_DISK_TOTAL,
633 stats->disk_total +
634 mirrorStats->total) < 0 ||
635 virTypedParamsAddULLong(&par, &npar, &maxpar,
636 VIR_DOMAIN_JOB_DISK_PROCESSED,
637 stats->disk_transferred +
638 mirrorStats->transferred) < 0 ||
639 virTypedParamsAddULLong(&par, &npar, &maxpar,
640 VIR_DOMAIN_JOB_DISK_REMAINING,
641 stats->disk_remaining +
642 mirrorRemaining) < 0)
643 goto error;
645 if (stats->disk_bps &&
646 virTypedParamsAddULLong(&par, &npar, &maxpar,
647 VIR_DOMAIN_JOB_DISK_BPS,
648 stats->disk_bps) < 0)
649 goto error;
651 if (stats->xbzrle_set) {
652 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
653 VIR_DOMAIN_JOB_COMPRESSION_CACHE,
654 stats->xbzrle_cache_size) < 0 ||
655 virTypedParamsAddULLong(&par, &npar, &maxpar,
656 VIR_DOMAIN_JOB_COMPRESSION_BYTES,
657 stats->xbzrle_bytes) < 0 ||
658 virTypedParamsAddULLong(&par, &npar, &maxpar,
659 VIR_DOMAIN_JOB_COMPRESSION_PAGES,
660 stats->xbzrle_pages) < 0 ||
661 virTypedParamsAddULLong(&par, &npar, &maxpar,
662 VIR_DOMAIN_JOB_COMPRESSION_CACHE_MISSES,
663 stats->xbzrle_cache_miss) < 0 ||
664 virTypedParamsAddULLong(&par, &npar, &maxpar,
665 VIR_DOMAIN_JOB_COMPRESSION_OVERFLOW,
666 stats->xbzrle_overflow) < 0)
667 goto error;
670 if (stats->cpu_throttle_percentage &&
671 virTypedParamsAddInt(&par, &npar, &maxpar,
672 VIR_DOMAIN_JOB_AUTO_CONVERGE_THROTTLE,
673 stats->cpu_throttle_percentage) < 0)
674 goto error;
676 done:
677 *type = qemuDomainJobStatusToType(jobInfo->status);
678 *params = par;
679 *nparams = npar;
680 return 0;
682 error:
683 virTypedParamsFree(par, npar);
684 return -1;
688 static int
689 qemuDomainDumpJobInfoToParams(qemuDomainJobInfoPtr jobInfo,
690 int *type,
691 virTypedParameterPtr *params,
692 int *nparams)
694 qemuMonitorDumpStats *stats = &jobInfo->stats.dump;
695 virTypedParameterPtr par = NULL;
696 int maxpar = 0;
697 int npar = 0;
699 if (virTypedParamsAddInt(&par, &npar, &maxpar,
700 VIR_DOMAIN_JOB_OPERATION,
701 jobInfo->operation) < 0)
702 goto error;
704 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
705 VIR_DOMAIN_JOB_TIME_ELAPSED,
706 jobInfo->timeElapsed) < 0)
707 goto error;
709 if (virTypedParamsAddULLong(&par, &npar, &maxpar,
710 VIR_DOMAIN_JOB_MEMORY_TOTAL,
711 stats->total) < 0 ||
712 virTypedParamsAddULLong(&par, &npar, &maxpar,
713 VIR_DOMAIN_JOB_MEMORY_PROCESSED,
714 stats->completed) < 0 ||
715 virTypedParamsAddULLong(&par, &npar, &maxpar,
716 VIR_DOMAIN_JOB_MEMORY_REMAINING,
717 stats->total - stats->completed) < 0)
718 goto error;
720 *type = qemuDomainJobStatusToType(jobInfo->status);
721 *params = par;
722 *nparams = npar;
723 return 0;
725 error:
726 virTypedParamsFree(par, npar);
727 return -1;
732 qemuDomainJobInfoToParams(qemuDomainJobInfoPtr jobInfo,
733 int *type,
734 virTypedParameterPtr *params,
735 int *nparams)
737 switch (jobInfo->statsType) {
738 case QEMU_DOMAIN_JOB_STATS_TYPE_MIGRATION:
739 case QEMU_DOMAIN_JOB_STATS_TYPE_SAVEDUMP:
740 return qemuDomainMigrationJobInfoToParams(jobInfo, type, params, nparams);
742 case QEMU_DOMAIN_JOB_STATS_TYPE_MEMDUMP:
743 return qemuDomainDumpJobInfoToParams(jobInfo, type, params, nparams);
745 case QEMU_DOMAIN_JOB_STATS_TYPE_NONE:
746 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
747 _("invalid job statistics type"));
748 break;
750 default:
751 virReportEnumRangeError(qemuDomainJobStatsType, jobInfo->statsType);
752 break;
755 return -1;
759 /* qemuDomainGetMasterKeyFilePath:
760 * @libDir: Directory path to domain lib files
762 * Generate a path to the domain master key file for libDir.
763 * It's up to the caller to handle checking if path exists.
765 * Returns path to memory containing the name of the file. It is up to the
766 * caller to free; otherwise, NULL on failure.
768 char *
769 qemuDomainGetMasterKeyFilePath(const char *libDir)
771 if (!libDir) {
772 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
773 _("invalid path for master key file"));
774 return NULL;
776 return virFileBuildPath(libDir, "master-key.aes", NULL);
780 /* qemuDomainWriteMasterKeyFile:
781 * @driver: qemu driver data
782 * @vm: Pointer to the vm object
784 * Get the desired path to the masterKey file and store it in the path.
786 * Returns 0 on success, -1 on failure with error message indicating failure
789 qemuDomainWriteMasterKeyFile(virQEMUDriverPtr driver,
790 virDomainObjPtr vm)
792 char *path;
793 int fd = -1;
794 int ret = -1;
795 qemuDomainObjPrivatePtr priv = vm->privateData;
797 /* Only gets filled in if we have the capability */
798 if (!priv->masterKey)
799 return 0;
801 if (!(path = qemuDomainGetMasterKeyFilePath(priv->libDir)))
802 return -1;
804 if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0600)) < 0) {
805 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
806 _("failed to open domain master key file for write"));
807 goto cleanup;
810 if (safewrite(fd, priv->masterKey, priv->masterKeyLen) < 0) {
811 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
812 _("failed to write master key file for domain"));
813 goto cleanup;
816 if (qemuSecurityDomainSetPathLabel(driver, vm, path, false) < 0)
817 goto cleanup;
819 ret = 0;
821 cleanup:
822 VIR_FORCE_CLOSE(fd);
823 VIR_FREE(path);
825 return ret;
829 static void
830 qemuDomainMasterKeyFree(qemuDomainObjPrivatePtr priv)
832 if (!priv->masterKey)
833 return;
835 VIR_DISPOSE_N(priv->masterKey, priv->masterKeyLen);
838 /* qemuDomainMasterKeyReadFile:
839 * @priv: pointer to domain private object
841 * Expected to be called during qemuProcessReconnect once the domain
842 * libDir has been generated through qemuStateInitialize calling
843 * virDomainObjListLoadAllConfigs which will restore the libDir path
844 * to the domain private object.
846 * This function will get the path to the master key file and if it
847 * exists, it will read the contents of the file saving it in priv->masterKey.
849 * Once the file exists, the validity checks may cause failures; however,
850 * if the file doesn't exist or the capability doesn't exist, we just
851 * return (mostly) quietly.
853 * Returns 0 on success or lack of capability
854 * -1 on failure with error message indicating failure
857 qemuDomainMasterKeyReadFile(qemuDomainObjPrivatePtr priv)
859 char *path;
860 int fd = -1;
861 uint8_t *masterKey = NULL;
862 ssize_t masterKeyLen = 0;
864 /* If we don't have the capability, then do nothing. */
865 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET))
866 return 0;
868 if (!(path = qemuDomainGetMasterKeyFilePath(priv->libDir)))
869 return -1;
871 if (!virFileExists(path)) {
872 virReportError(VIR_ERR_INTERNAL_ERROR,
873 _("domain master key file doesn't exist in %s"),
874 priv->libDir);
875 goto error;
878 if ((fd = open(path, O_RDONLY)) < 0) {
879 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
880 _("failed to open domain master key file for read"));
881 goto error;
884 if (VIR_ALLOC_N(masterKey, 1024) < 0)
885 goto error;
887 if ((masterKeyLen = saferead(fd, masterKey, 1024)) < 0) {
888 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
889 _("unable to read domain master key file"));
890 goto error;
893 if (masterKeyLen != QEMU_DOMAIN_MASTER_KEY_LEN) {
894 virReportError(VIR_ERR_INTERNAL_ERROR,
895 _("invalid master key read, size=%zd"), masterKeyLen);
896 goto error;
899 ignore_value(VIR_REALLOC_N_QUIET(masterKey, masterKeyLen));
901 priv->masterKey = masterKey;
902 priv->masterKeyLen = masterKeyLen;
904 VIR_FORCE_CLOSE(fd);
905 VIR_FREE(path);
907 return 0;
909 error:
910 if (masterKeyLen > 0)
911 memset(masterKey, 0, masterKeyLen);
912 VIR_FREE(masterKey);
914 VIR_FORCE_CLOSE(fd);
915 VIR_FREE(path);
917 return -1;
921 /* qemuDomainMasterKeyRemove:
922 * @priv: Pointer to the domain private object
924 * Remove the traces of the master key, clear the heap, clear the file,
925 * delete the file.
927 void
928 qemuDomainMasterKeyRemove(qemuDomainObjPrivatePtr priv)
930 char *path = NULL;
932 if (!priv->masterKey)
933 return;
935 /* Clear the contents */
936 qemuDomainMasterKeyFree(priv);
938 /* Delete the master key file */
939 path = qemuDomainGetMasterKeyFilePath(priv->libDir);
940 unlink(path);
942 VIR_FREE(path);
946 /* qemuDomainMasterKeyCreate:
947 * @vm: Pointer to the domain object
949 * As long as the underlying qemu has the secret capability,
950 * generate and store 'raw' in a file a random 32-byte key to
951 * be used as a secret shared with qemu to share sensitive data.
953 * Returns: 0 on success, -1 w/ error message on failure
956 qemuDomainMasterKeyCreate(virDomainObjPtr vm)
958 qemuDomainObjPrivatePtr priv = vm->privateData;
960 /* If we don't have the capability, then do nothing. */
961 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET))
962 return 0;
964 if (VIR_ALLOC_N(priv->masterKey, QEMU_DOMAIN_MASTER_KEY_LEN) < 0)
965 return -1;
966 priv->masterKeyLen = QEMU_DOMAIN_MASTER_KEY_LEN;
968 if (virRandomBytes(priv->masterKey, priv->masterKeyLen) < 0) {
969 VIR_DISPOSE_N(priv->masterKey, priv->masterKeyLen);
970 return -1;
973 return 0;
977 static void
978 qemuDomainSecretPlainClear(qemuDomainSecretPlainPtr secret)
980 VIR_FREE(secret->username);
981 VIR_DISPOSE_N(secret->secret, secret->secretlen);
985 static void
986 qemuDomainSecretAESClear(qemuDomainSecretAESPtr secret,
987 bool keepAlias)
989 if (!keepAlias)
990 VIR_FREE(secret->alias);
992 VIR_FREE(secret->username);
993 VIR_FREE(secret->iv);
994 VIR_FREE(secret->ciphertext);
998 static void
999 qemuDomainSecretInfoClear(qemuDomainSecretInfoPtr secinfo,
1000 bool keepAlias)
1002 if (!secinfo)
1003 return;
1005 switch ((qemuDomainSecretInfoType) secinfo->type) {
1006 case VIR_DOMAIN_SECRET_INFO_TYPE_PLAIN:
1007 qemuDomainSecretPlainClear(&secinfo->s.plain);
1008 break;
1010 case VIR_DOMAIN_SECRET_INFO_TYPE_AES:
1011 qemuDomainSecretAESClear(&secinfo->s.aes, keepAlias);
1012 break;
1014 case VIR_DOMAIN_SECRET_INFO_TYPE_LAST:
1015 break;
1020 void
1021 qemuDomainSecretInfoFree(qemuDomainSecretInfoPtr *secinfo)
1023 if (!*secinfo)
1024 return;
1026 qemuDomainSecretInfoClear(*secinfo, false);
1028 VIR_FREE(*secinfo);
1033 * qemuDomainSecretInfoDestroy:
1034 * @secinfo: object to destroy
1036 * Removes any data unnecessary for further use, but keeps alias allocated.
1038 void
1039 qemuDomainSecretInfoDestroy(qemuDomainSecretInfoPtr secinfo)
1041 qemuDomainSecretInfoClear(secinfo, true);
1045 static virClassPtr qemuDomainDiskPrivateClass;
1046 static void qemuDomainDiskPrivateDispose(void *obj);
1048 static int
1049 qemuDomainDiskPrivateOnceInit(void)
1051 if (!VIR_CLASS_NEW(qemuDomainDiskPrivate, virClassForObject()))
1052 return -1;
1054 return 0;
1057 VIR_ONCE_GLOBAL_INIT(qemuDomainDiskPrivate);
1059 static virObjectPtr
1060 qemuDomainDiskPrivateNew(void)
1062 qemuDomainDiskPrivatePtr priv;
1064 if (qemuDomainDiskPrivateInitialize() < 0)
1065 return NULL;
1067 if (!(priv = virObjectNew(qemuDomainDiskPrivateClass)))
1068 return NULL;
1070 return (virObjectPtr) priv;
1073 static void
1074 qemuDomainDiskPrivateDispose(void *obj)
1076 qemuDomainDiskPrivatePtr priv = obj;
1078 virObjectUnref(priv->migrSource);
1079 VIR_FREE(priv->qomName);
1080 VIR_FREE(priv->nodeCopyOnRead);
1081 virObjectUnref(priv->blockjob);
1084 static virClassPtr qemuDomainStorageSourcePrivateClass;
1085 static void qemuDomainStorageSourcePrivateDispose(void *obj);
1087 static int
1088 qemuDomainStorageSourcePrivateOnceInit(void)
1090 if (!VIR_CLASS_NEW(qemuDomainStorageSourcePrivate, virClassForObject()))
1091 return -1;
1093 return 0;
1096 VIR_ONCE_GLOBAL_INIT(qemuDomainStorageSourcePrivate);
1098 virObjectPtr
1099 qemuDomainStorageSourcePrivateNew(void)
1101 qemuDomainStorageSourcePrivatePtr priv;
1103 if (qemuDomainStorageSourcePrivateInitialize() < 0)
1104 return NULL;
1106 if (!(priv = virObjectNew(qemuDomainStorageSourcePrivateClass)))
1107 return NULL;
1109 return (virObjectPtr) priv;
1113 static void
1114 qemuDomainStorageSourcePrivateDispose(void *obj)
1116 qemuDomainStorageSourcePrivatePtr priv = obj;
1118 qemuDomainSecretInfoFree(&priv->secinfo);
1119 qemuDomainSecretInfoFree(&priv->encinfo);
1123 static virClassPtr qemuDomainVcpuPrivateClass;
1124 static void qemuDomainVcpuPrivateDispose(void *obj);
1126 static int
1127 qemuDomainVcpuPrivateOnceInit(void)
1129 if (!VIR_CLASS_NEW(qemuDomainVcpuPrivate, virClassForObject()))
1130 return -1;
1132 return 0;
1135 VIR_ONCE_GLOBAL_INIT(qemuDomainVcpuPrivate);
1137 static virObjectPtr
1138 qemuDomainVcpuPrivateNew(void)
1140 qemuDomainVcpuPrivatePtr priv;
1142 if (qemuDomainVcpuPrivateInitialize() < 0)
1143 return NULL;
1145 if (!(priv = virObjectNew(qemuDomainVcpuPrivateClass)))
1146 return NULL;
1148 return (virObjectPtr) priv;
1152 static void
1153 qemuDomainVcpuPrivateDispose(void *obj)
1155 qemuDomainVcpuPrivatePtr priv = obj;
1157 VIR_FREE(priv->type);
1158 VIR_FREE(priv->alias);
1159 return;
1163 static virClassPtr qemuDomainChrSourcePrivateClass;
1164 static void qemuDomainChrSourcePrivateDispose(void *obj);
1166 static int
1167 qemuDomainChrSourcePrivateOnceInit(void)
1169 if (!VIR_CLASS_NEW(qemuDomainChrSourcePrivate, virClassForObject()))
1170 return -1;
1172 return 0;
1175 VIR_ONCE_GLOBAL_INIT(qemuDomainChrSourcePrivate);
1177 static virObjectPtr
1178 qemuDomainChrSourcePrivateNew(void)
1180 qemuDomainChrSourcePrivatePtr priv;
1182 if (qemuDomainChrSourcePrivateInitialize() < 0)
1183 return NULL;
1185 if (!(priv = virObjectNew(qemuDomainChrSourcePrivateClass)))
1186 return NULL;
1188 return (virObjectPtr) priv;
1192 static void
1193 qemuDomainChrSourcePrivateDispose(void *obj)
1195 qemuDomainChrSourcePrivatePtr priv = obj;
1197 qemuDomainSecretInfoFree(&priv->secinfo);
1201 static virClassPtr qemuDomainVsockPrivateClass;
1202 static void qemuDomainVsockPrivateDispose(void *obj);
1204 static int
1205 qemuDomainVsockPrivateOnceInit(void)
1207 if (!VIR_CLASS_NEW(qemuDomainVsockPrivate, virClassForObject()))
1208 return -1;
1210 return 0;
1213 VIR_ONCE_GLOBAL_INIT(qemuDomainVsockPrivate);
1215 static virObjectPtr
1216 qemuDomainVsockPrivateNew(void)
1218 qemuDomainVsockPrivatePtr priv;
1220 if (qemuDomainVsockPrivateInitialize() < 0)
1221 return NULL;
1223 if (!(priv = virObjectNew(qemuDomainVsockPrivateClass)))
1224 return NULL;
1226 priv->vhostfd = -1;
1228 return (virObjectPtr) priv;
1232 static void
1233 qemuDomainVsockPrivateDispose(void *obj ATTRIBUTE_UNUSED)
1235 qemuDomainVsockPrivatePtr priv = obj;
1237 VIR_FORCE_CLOSE(priv->vhostfd);
1241 static virClassPtr qemuDomainGraphicsPrivateClass;
1242 static void qemuDomainGraphicsPrivateDispose(void *obj);
1244 static int
1245 qemuDomainGraphicsPrivateOnceInit(void)
1247 if (!VIR_CLASS_NEW(qemuDomainGraphicsPrivate, virClassForObject()))
1248 return -1;
1250 return 0;
1253 VIR_ONCE_GLOBAL_INIT(qemuDomainGraphicsPrivate);
1255 static virObjectPtr
1256 qemuDomainGraphicsPrivateNew(void)
1258 qemuDomainGraphicsPrivatePtr priv;
1260 if (qemuDomainGraphicsPrivateInitialize() < 0)
1261 return NULL;
1263 if (!(priv = virObjectNew(qemuDomainGraphicsPrivateClass)))
1264 return NULL;
1266 return (virObjectPtr) priv;
1270 static void
1271 qemuDomainGraphicsPrivateDispose(void *obj)
1273 qemuDomainGraphicsPrivatePtr priv = obj;
1275 VIR_FREE(priv->tlsAlias);
1276 qemuDomainSecretInfoFree(&priv->secinfo);
1280 /* qemuDomainSecretPlainSetup:
1281 * @secinfo: Pointer to secret info
1282 * @usageType: The virSecretUsageType
1283 * @username: username to use for authentication (may be NULL)
1284 * @seclookupdef: Pointer to seclookupdef data
1286 * Taking a secinfo, fill in the plaintext information
1288 * Returns 0 on success, -1 on failure with error message
1290 static int
1291 qemuDomainSecretPlainSetup(qemuDomainSecretInfoPtr secinfo,
1292 virSecretUsageType usageType,
1293 const char *username,
1294 virSecretLookupTypeDefPtr seclookupdef)
1296 virConnectPtr conn;
1297 int ret = -1;
1299 conn = virGetConnectSecret();
1300 if (!conn)
1301 return -1;
1303 secinfo->type = VIR_DOMAIN_SECRET_INFO_TYPE_PLAIN;
1304 if (VIR_STRDUP(secinfo->s.plain.username, username) < 0)
1305 goto cleanup;
1307 ret = virSecretGetSecretString(conn, seclookupdef, usageType,
1308 &secinfo->s.plain.secret,
1309 &secinfo->s.plain.secretlen);
1311 cleanup:
1312 virObjectUnref(conn);
1313 return ret;
1317 /* qemuDomainSecretAESSetup:
1318 * @priv: pointer to domain private object
1319 * @secinfo: Pointer to secret info
1320 * @srcalias: Alias of the disk/hostdev used to generate the secret alias
1321 * @usageType: The virSecretUsageType
1322 * @username: username to use for authentication (may be NULL)
1323 * @seclookupdef: Pointer to seclookupdef data
1324 * @isLuks: True/False for is for luks (alias generation)
1326 * Taking a secinfo, fill in the AES specific information using the
1328 * Returns 0 on success, -1 on failure with error message
1330 static int
1331 qemuDomainSecretAESSetup(qemuDomainObjPrivatePtr priv,
1332 qemuDomainSecretInfoPtr secinfo,
1333 const char *srcalias,
1334 virSecretUsageType usageType,
1335 const char *username,
1336 virSecretLookupTypeDefPtr seclookupdef,
1337 bool isLuks)
1339 virConnectPtr conn;
1340 int ret = -1;
1341 uint8_t *raw_iv = NULL;
1342 size_t ivlen = QEMU_DOMAIN_AES_IV_LEN;
1343 uint8_t *secret = NULL;
1344 size_t secretlen = 0;
1345 uint8_t *ciphertext = NULL;
1346 size_t ciphertextlen = 0;
1348 conn = virGetConnectSecret();
1349 if (!conn)
1350 return -1;
1352 secinfo->type = VIR_DOMAIN_SECRET_INFO_TYPE_AES;
1353 if (VIR_STRDUP(secinfo->s.aes.username, username) < 0)
1354 goto cleanup;
1356 if (!(secinfo->s.aes.alias = qemuDomainGetSecretAESAlias(srcalias, isLuks)))
1357 goto cleanup;
1359 if (VIR_ALLOC_N(raw_iv, ivlen) < 0)
1360 goto cleanup;
1362 /* Create a random initialization vector */
1363 if (virRandomBytes(raw_iv, ivlen) < 0)
1364 goto cleanup;
1366 /* Encode the IV and save that since qemu will need it */
1367 if (!(secinfo->s.aes.iv = virStringEncodeBase64(raw_iv, ivlen)))
1368 goto cleanup;
1370 /* Grab the unencoded secret */
1371 if (virSecretGetSecretString(conn, seclookupdef, usageType,
1372 &secret, &secretlen) < 0)
1373 goto cleanup;
1375 if (virCryptoEncryptData(VIR_CRYPTO_CIPHER_AES256CBC,
1376 priv->masterKey, QEMU_DOMAIN_MASTER_KEY_LEN,
1377 raw_iv, ivlen, secret, secretlen,
1378 &ciphertext, &ciphertextlen) < 0)
1379 goto cleanup;
1381 /* Clear out the secret */
1382 memset(secret, 0, secretlen);
1384 /* Now encode the ciphertext and store to be passed to qemu */
1385 if (!(secinfo->s.aes.ciphertext = virStringEncodeBase64(ciphertext,
1386 ciphertextlen)))
1387 goto cleanup;
1389 ret = 0;
1391 cleanup:
1392 VIR_DISPOSE_N(raw_iv, ivlen);
1393 VIR_DISPOSE_N(secret, secretlen);
1394 VIR_DISPOSE_N(ciphertext, ciphertextlen);
1395 virObjectUnref(conn);
1396 return ret;
1401 * qemuDomainSupportsEncryptedSecret:
1402 * @priv: qemu domain private data
1404 * Returns true if libvirt can use encrypted 'secret' objects with VM which
1405 * @priv belongs to.
1407 bool
1408 qemuDomainSupportsEncryptedSecret(qemuDomainObjPrivatePtr priv)
1410 return virCryptoHaveCipher(VIR_CRYPTO_CIPHER_AES256CBC) &&
1411 virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET) &&
1412 priv->masterKey;
1416 /* qemuDomainSecretInfoNewPlain:
1417 * @usageType: Secret usage type
1418 * @username: username
1419 * @lookupDef: lookup def describing secret
1421 * Helper function to create a secinfo to be used for secinfo consumers. This
1422 * sets up a 'plain' (unencrypted) secret for legacy consumers.
1424 * Returns @secinfo on success, NULL on failure. Caller is responsible
1425 * to eventually free @secinfo.
1427 static qemuDomainSecretInfoPtr
1428 qemuDomainSecretInfoNewPlain(virSecretUsageType usageType,
1429 const char *username,
1430 virSecretLookupTypeDefPtr lookupDef)
1432 qemuDomainSecretInfoPtr secinfo = NULL;
1434 if (VIR_ALLOC(secinfo) < 0)
1435 return NULL;
1437 if (qemuDomainSecretPlainSetup(secinfo, usageType, username, lookupDef) < 0) {
1438 qemuDomainSecretInfoFree(&secinfo);
1439 return NULL;
1442 return secinfo;
1446 /* qemuDomainSecretInfoNew:
1447 * @priv: pointer to domain private object
1448 * @srcAlias: Alias base to use for TLS object
1449 * @usageType: Secret usage type
1450 * @username: username
1451 * @looupDef: lookup def describing secret
1452 * @isLuks: boolean for luks lookup
1454 * Helper function to create a secinfo to be used for secinfo consumers. This
1455 * sets up encrypted data to be used with qemu's 'secret' object.
1457 * Returns @secinfo on success, NULL on failure. Caller is responsible
1458 * to eventually free @secinfo.
1460 static qemuDomainSecretInfoPtr
1461 qemuDomainSecretInfoNew(qemuDomainObjPrivatePtr priv,
1462 const char *srcAlias,
1463 virSecretUsageType usageType,
1464 const char *username,
1465 virSecretLookupTypeDefPtr lookupDef,
1466 bool isLuks)
1468 qemuDomainSecretInfoPtr secinfo = NULL;
1470 if (!qemuDomainSupportsEncryptedSecret(priv)) {
1471 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1472 _("encrypted secrets are not supported"));
1473 return NULL;
1476 if (VIR_ALLOC(secinfo) < 0)
1477 return NULL;
1479 if (qemuDomainSecretAESSetup(priv, secinfo, srcAlias, usageType, username,
1480 lookupDef, isLuks) < 0) {
1481 qemuDomainSecretInfoFree(&secinfo);
1482 return NULL;
1485 return secinfo;
1490 * qemuDomainSecretInfoTLSNew:
1491 * @priv: pointer to domain private object
1492 * @srcAlias: Alias base to use for TLS object
1493 * @secretUUID: Provide a secretUUID value to look up/create the secretInfo
1495 * Using the passed @secretUUID, generate a seclookupdef that can be used
1496 * to generate the returned qemuDomainSecretInfoPtr for a TLS based secret.
1498 * Returns qemuDomainSecretInfoPtr or NULL on error.
1500 qemuDomainSecretInfoPtr
1501 qemuDomainSecretInfoTLSNew(qemuDomainObjPrivatePtr priv,
1502 const char *srcAlias,
1503 const char *secretUUID)
1505 virSecretLookupTypeDef seclookupdef = {0};
1507 if (virUUIDParse(secretUUID, seclookupdef.u.uuid) < 0) {
1508 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1509 _("malformed TLS secret uuid '%s' provided"),
1510 secretUUID);
1511 return NULL;
1513 seclookupdef.type = VIR_SECRET_LOOKUP_TYPE_UUID;
1515 return qemuDomainSecretInfoNew(priv, srcAlias,
1516 VIR_SECRET_USAGE_TYPE_TLS, NULL,
1517 &seclookupdef, false);
1521 void
1522 qemuDomainSecretDiskDestroy(virDomainDiskDefPtr disk)
1524 qemuDomainStorageSourcePrivatePtr srcPriv;
1525 virStorageSourcePtr n;
1527 for (n = disk->src; virStorageSourceIsBacking(n); n = n->backingStore) {
1528 if ((srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(n))) {
1529 qemuDomainSecretInfoDestroy(srcPriv->secinfo);
1530 qemuDomainSecretInfoDestroy(srcPriv->encinfo);
1536 bool
1537 qemuDomainStorageSourceHasAuth(virStorageSourcePtr src)
1539 if (!virStorageSourceIsEmpty(src) &&
1540 virStorageSourceGetActualType(src) == VIR_STORAGE_TYPE_NETWORK &&
1541 src->auth &&
1542 (src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI ||
1543 src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD))
1544 return true;
1546 return false;
1550 bool
1551 qemuDomainDiskHasEncryptionSecret(virStorageSourcePtr src)
1553 if (!virStorageSourceIsEmpty(src) && src->encryption &&
1554 src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_LUKS &&
1555 src->encryption->nsecrets > 0)
1556 return true;
1558 return false;
1563 * qemuDomainSecretStorageSourcePrepare:
1564 * @priv: domain private object
1565 * @src: storage source struct to setup
1566 * @authalias: prefix of the alias for secret holding authentication data
1567 * @encalias: prefix of the alias for secret holding encryption password
1569 * Prepares data necessary for encryption and authentication of @src. The two
1570 * alias prefixes are provided since in the backing chain authentication belongs
1571 * to the storage protocol data whereas encryption is relevant to the format
1572 * driver in qemu. The two will have different node names.
1574 * Returns 0 on success; -1 on error while reporting an libvirt error.
1576 static int
1577 qemuDomainSecretStorageSourcePrepare(qemuDomainObjPrivatePtr priv,
1578 virStorageSourcePtr src,
1579 const char *authalias,
1580 const char *encalias)
1582 qemuDomainStorageSourcePrivatePtr srcPriv;
1583 bool iscsiHasPS = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_ISCSI_PASSWORD_SECRET);
1584 bool hasAuth = qemuDomainStorageSourceHasAuth(src);
1585 bool hasEnc = qemuDomainDiskHasEncryptionSecret(src);
1587 if (!hasAuth && !hasEnc)
1588 return 0;
1590 if (!(src->privateData = qemuDomainStorageSourcePrivateNew()))
1591 return -1;
1593 srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
1595 if (hasAuth) {
1596 virSecretUsageType usageType = VIR_SECRET_USAGE_TYPE_ISCSI;
1598 if (src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD)
1599 usageType = VIR_SECRET_USAGE_TYPE_CEPH;
1601 if (!qemuDomainSupportsEncryptedSecret(priv) ||
1602 (src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI && !iscsiHasPS)) {
1603 srcPriv->secinfo = qemuDomainSecretInfoNewPlain(usageType,
1604 src->auth->username,
1605 &src->auth->seclookupdef);
1606 } else {
1607 srcPriv->secinfo = qemuDomainSecretInfoNew(priv, authalias,
1608 usageType,
1609 src->auth->username,
1610 &src->auth->seclookupdef,
1611 false);
1614 if (!srcPriv->secinfo)
1615 return -1;
1618 if (hasEnc) {
1619 if (!(srcPriv->encinfo =
1620 qemuDomainSecretInfoNew(priv, encalias,
1621 VIR_SECRET_USAGE_TYPE_VOLUME, NULL,
1622 &src->encryption->secrets[0]->seclookupdef,
1623 true)))
1624 return -1;
1627 return 0;
1631 void
1632 qemuDomainSecretHostdevDestroy(virDomainHostdevDefPtr hostdev)
1634 qemuDomainStorageSourcePrivatePtr srcPriv;
1636 if (virHostdevIsSCSIDevice(hostdev)) {
1637 virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1638 virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
1640 if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
1641 srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(iscsisrc->src);
1642 if (srcPriv && srcPriv->secinfo)
1643 qemuDomainSecretInfoFree(&srcPriv->secinfo);
1649 /* qemuDomainSecretHostdevPrepare:
1650 * @priv: pointer to domain private object
1651 * @hostdev: Pointer to a hostdev definition
1653 * For the right host device, generate the qemuDomainSecretInfo structure.
1655 * Returns 0 on success, -1 on failure
1658 qemuDomainSecretHostdevPrepare(qemuDomainObjPrivatePtr priv,
1659 virDomainHostdevDefPtr hostdev)
1661 if (virHostdevIsSCSIDevice(hostdev)) {
1662 virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1663 virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
1664 virStorageSourcePtr src = iscsisrc->src;
1666 if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI &&
1667 src->auth) {
1668 if (qemuDomainSecretStorageSourcePrepare(priv, src,
1669 hostdev->info->alias, NULL) < 0)
1670 return -1;
1674 return 0;
1678 void
1679 qemuDomainSecretChardevDestroy(virDomainChrSourceDefPtr dev)
1681 qemuDomainChrSourcePrivatePtr chrSourcePriv =
1682 QEMU_DOMAIN_CHR_SOURCE_PRIVATE(dev);
1684 if (!chrSourcePriv || !chrSourcePriv->secinfo)
1685 return;
1687 qemuDomainSecretInfoFree(&chrSourcePriv->secinfo);
1691 /* qemuDomainSecretChardevPrepare:
1692 * @cfg: Pointer to driver config object
1693 * @priv: pointer to domain private object
1694 * @chrAlias: Alias of the chr device
1695 * @dev: Pointer to a char source definition
1697 * For a TCP character device, generate a qemuDomainSecretInfo to be used
1698 * by the command line code to generate the secret for the tls-creds to use.
1700 * Returns 0 on success, -1 on failure
1703 qemuDomainSecretChardevPrepare(virQEMUDriverConfigPtr cfg,
1704 qemuDomainObjPrivatePtr priv,
1705 const char *chrAlias,
1706 virDomainChrSourceDefPtr dev)
1708 char *charAlias = NULL;
1710 if (dev->type != VIR_DOMAIN_CHR_TYPE_TCP)
1711 return 0;
1713 if (dev->data.tcp.haveTLS == VIR_TRISTATE_BOOL_YES &&
1714 cfg->chardevTLSx509secretUUID) {
1715 qemuDomainChrSourcePrivatePtr chrSourcePriv =
1716 QEMU_DOMAIN_CHR_SOURCE_PRIVATE(dev);
1718 if (!(charAlias = qemuAliasChardevFromDevAlias(chrAlias)))
1719 return -1;
1721 chrSourcePriv->secinfo =
1722 qemuDomainSecretInfoTLSNew(priv, charAlias,
1723 cfg->chardevTLSx509secretUUID);
1724 VIR_FREE(charAlias);
1726 if (!chrSourcePriv->secinfo)
1727 return -1;
1730 return 0;
1734 static void
1735 qemuDomainSecretGraphicsDestroy(virDomainGraphicsDefPtr graphics)
1737 qemuDomainGraphicsPrivatePtr gfxPriv = QEMU_DOMAIN_GRAPHICS_PRIVATE(graphics);
1739 if (!gfxPriv)
1740 return;
1742 VIR_FREE(gfxPriv->tlsAlias);
1743 qemuDomainSecretInfoFree(&gfxPriv->secinfo);
1747 static int
1748 qemuDomainSecretGraphicsPrepare(virQEMUDriverConfigPtr cfg,
1749 qemuDomainObjPrivatePtr priv,
1750 virDomainGraphicsDefPtr graphics)
1752 virQEMUCapsPtr qemuCaps = priv->qemuCaps;
1753 qemuDomainGraphicsPrivatePtr gfxPriv = QEMU_DOMAIN_GRAPHICS_PRIVATE(graphics);
1755 if (graphics->type != VIR_DOMAIN_GRAPHICS_TYPE_VNC)
1756 return 0;
1758 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_TLS_CREDS_X509))
1759 return 0;
1761 if (!cfg->vncTLS)
1762 return 0;
1764 if (VIR_STRDUP(gfxPriv->tlsAlias, "vnc-tls-creds0") < 0)
1765 return -1;
1767 if (cfg->vncTLSx509secretUUID) {
1768 gfxPriv->secinfo = qemuDomainSecretInfoTLSNew(priv, gfxPriv->tlsAlias,
1769 cfg->vncTLSx509secretUUID);
1770 if (!gfxPriv->secinfo)
1771 return -1;
1774 return 0;
1778 /* qemuDomainSecretDestroy:
1779 * @vm: Domain object
1781 * Removes all unnecessary data which was needed to generate 'secret' objects.
1783 void
1784 qemuDomainSecretDestroy(virDomainObjPtr vm)
1786 size_t i;
1788 for (i = 0; i < vm->def->ndisks; i++)
1789 qemuDomainSecretDiskDestroy(vm->def->disks[i]);
1791 for (i = 0; i < vm->def->nhostdevs; i++)
1792 qemuDomainSecretHostdevDestroy(vm->def->hostdevs[i]);
1794 for (i = 0; i < vm->def->nserials; i++)
1795 qemuDomainSecretChardevDestroy(vm->def->serials[i]->source);
1797 for (i = 0; i < vm->def->nparallels; i++)
1798 qemuDomainSecretChardevDestroy(vm->def->parallels[i]->source);
1800 for (i = 0; i < vm->def->nchannels; i++)
1801 qemuDomainSecretChardevDestroy(vm->def->channels[i]->source);
1803 for (i = 0; i < vm->def->nconsoles; i++)
1804 qemuDomainSecretChardevDestroy(vm->def->consoles[i]->source);
1806 for (i = 0; i < vm->def->nsmartcards; i++) {
1807 if (vm->def->smartcards[i]->type ==
1808 VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH)
1809 qemuDomainSecretChardevDestroy(vm->def->smartcards[i]->data.passthru);
1812 for (i = 0; i < vm->def->nrngs; i++) {
1813 if (vm->def->rngs[i]->backend == VIR_DOMAIN_RNG_BACKEND_EGD)
1814 qemuDomainSecretChardevDestroy(vm->def->rngs[i]->source.chardev);
1817 for (i = 0; i < vm->def->nredirdevs; i++)
1818 qemuDomainSecretChardevDestroy(vm->def->redirdevs[i]->source);
1820 for (i = 0; i < vm->def->ngraphics; i++)
1821 qemuDomainSecretGraphicsDestroy(vm->def->graphics[i]);
1825 /* qemuDomainSecretPrepare:
1826 * @driver: Pointer to driver object
1827 * @vm: Domain object
1829 * For any objects that may require an auth/secret setup, create a
1830 * qemuDomainSecretInfo and save it in the appropriate place within
1831 * the private structures. This will be used by command line build
1832 * code in order to pass the secret along to qemu in order to provide
1833 * the necessary authentication data.
1835 * Returns 0 on success, -1 on failure with error message set
1838 qemuDomainSecretPrepare(virQEMUDriverPtr driver,
1839 virDomainObjPtr vm)
1841 qemuDomainObjPrivatePtr priv = vm->privateData;
1842 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1843 size_t i;
1844 int ret = -1;
1846 /* disk secrets are prepared when preparing disks */
1848 for (i = 0; i < vm->def->nhostdevs; i++) {
1849 if (qemuDomainSecretHostdevPrepare(priv,
1850 vm->def->hostdevs[i]) < 0)
1851 goto cleanup;
1854 for (i = 0; i < vm->def->nserials; i++) {
1855 if (qemuDomainSecretChardevPrepare(cfg, priv,
1856 vm->def->serials[i]->info.alias,
1857 vm->def->serials[i]->source) < 0)
1858 goto cleanup;
1861 for (i = 0; i < vm->def->nparallels; i++) {
1862 if (qemuDomainSecretChardevPrepare(cfg, priv,
1863 vm->def->parallels[i]->info.alias,
1864 vm->def->parallels[i]->source) < 0)
1865 goto cleanup;
1868 for (i = 0; i < vm->def->nchannels; i++) {
1869 if (qemuDomainSecretChardevPrepare(cfg, priv,
1870 vm->def->channels[i]->info.alias,
1871 vm->def->channels[i]->source) < 0)
1872 goto cleanup;
1875 for (i = 0; i < vm->def->nconsoles; i++) {
1876 if (qemuDomainSecretChardevPrepare(cfg, priv,
1877 vm->def->consoles[i]->info.alias,
1878 vm->def->consoles[i]->source) < 0)
1879 goto cleanup;
1882 for (i = 0; i < vm->def->nsmartcards; i++)
1883 if (vm->def->smartcards[i]->type ==
1884 VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH &&
1885 qemuDomainSecretChardevPrepare(cfg, priv,
1886 vm->def->smartcards[i]->info.alias,
1887 vm->def->smartcards[i]->data.passthru) < 0)
1888 goto cleanup;
1890 for (i = 0; i < vm->def->nrngs; i++) {
1891 if (vm->def->rngs[i]->backend == VIR_DOMAIN_RNG_BACKEND_EGD &&
1892 qemuDomainSecretChardevPrepare(cfg, priv,
1893 vm->def->rngs[i]->info.alias,
1894 vm->def->rngs[i]->source.chardev) < 0)
1895 goto cleanup;
1898 for (i = 0; i < vm->def->nredirdevs; i++) {
1899 if (qemuDomainSecretChardevPrepare(cfg, priv,
1900 vm->def->redirdevs[i]->info.alias,
1901 vm->def->redirdevs[i]->source) < 0)
1902 goto cleanup;
1905 for (i = 0; i < vm->def->ngraphics; i++) {
1906 if (qemuDomainSecretGraphicsPrepare(cfg, priv, vm->def->graphics[i]) < 0)
1907 goto cleanup;
1910 ret = 0;
1912 cleanup:
1913 virObjectUnref(cfg);
1914 return ret;
1918 /* This is the old way of setting up per-domain directories */
1919 static int
1920 qemuDomainSetPrivatePathsOld(virQEMUDriverPtr driver,
1921 virDomainObjPtr vm)
1923 qemuDomainObjPrivatePtr priv = vm->privateData;
1924 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1925 int ret = -1;
1927 if (!priv->libDir &&
1928 virAsprintf(&priv->libDir, "%s/domain-%s",
1929 cfg->libDir, vm->def->name) < 0)
1930 goto cleanup;
1932 if (!priv->channelTargetDir &&
1933 virAsprintf(&priv->channelTargetDir, "%s/domain-%s",
1934 cfg->channelTargetDir, vm->def->name) < 0)
1935 goto cleanup;
1937 ret = 0;
1938 cleanup:
1939 virObjectUnref(cfg);
1940 return ret;
1945 qemuDomainSetPrivatePaths(virQEMUDriverPtr driver,
1946 virDomainObjPtr vm)
1948 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1949 qemuDomainObjPrivatePtr priv = vm->privateData;
1950 char *domname = virDomainDefGetShortName(vm->def);
1951 int ret = -1;
1953 if (!domname)
1954 goto cleanup;
1956 if (!priv->libDir &&
1957 virAsprintf(&priv->libDir, "%s/domain-%s", cfg->libDir, domname) < 0)
1958 goto cleanup;
1960 if (!priv->channelTargetDir &&
1961 virAsprintf(&priv->channelTargetDir, "%s/domain-%s",
1962 cfg->channelTargetDir, domname) < 0)
1963 goto cleanup;
1965 ret = 0;
1966 cleanup:
1967 virObjectUnref(cfg);
1968 VIR_FREE(domname);
1969 return ret;
1973 static void *
1974 qemuDomainObjPrivateAlloc(void *opaque)
1976 qemuDomainObjPrivatePtr priv;
1978 if (VIR_ALLOC(priv) < 0)
1979 return NULL;
1981 if (qemuDomainObjInitJob(priv) < 0) {
1982 virReportSystemError(errno, "%s",
1983 _("Unable to init qemu driver mutexes"));
1984 goto error;
1987 if (!(priv->devs = virChrdevAlloc()))
1988 goto error;
1990 priv->migMaxBandwidth = QEMU_DOMAIN_MIG_BANDWIDTH_MAX;
1991 priv->driver = opaque;
1993 return priv;
1995 error:
1996 VIR_FREE(priv);
1997 return NULL;
2001 * qemuDomainObjPrivateDataClear:
2002 * @priv: domain private data
2004 * Clears private data entries, which are not necessary or stale if the VM is
2005 * not running.
2007 void
2008 qemuDomainObjPrivateDataClear(qemuDomainObjPrivatePtr priv)
2010 virStringListFree(priv->qemuDevices);
2011 priv->qemuDevices = NULL;
2013 virCgroupFree(&priv->cgroup);
2015 virPerfFree(priv->perf);
2016 priv->perf = NULL;
2018 VIR_FREE(priv->machineName);
2020 virObjectUnref(priv->qemuCaps);
2021 priv->qemuCaps = NULL;
2023 VIR_FREE(priv->pidfile);
2025 VIR_FREE(priv->libDir);
2026 VIR_FREE(priv->channelTargetDir);
2028 priv->memPrealloc = false;
2030 /* remove automatic pinning data */
2031 virBitmapFree(priv->autoNodeset);
2032 priv->autoNodeset = NULL;
2033 virBitmapFree(priv->autoCpuset);
2034 priv->autoCpuset = NULL;
2036 /* remove address data */
2037 virDomainPCIAddressSetFree(priv->pciaddrs);
2038 priv->pciaddrs = NULL;
2039 virDomainUSBAddressSetFree(priv->usbaddrs);
2040 priv->usbaddrs = NULL;
2042 virCPUDefFree(priv->origCPU);
2043 priv->origCPU = NULL;
2045 /* clear previously used namespaces */
2046 virBitmapFree(priv->namespaces);
2047 priv->namespaces = NULL;
2049 priv->rememberOwner = false;
2051 priv->reconnectBlockjobs = VIR_TRISTATE_BOOL_ABSENT;
2052 priv->allowReboot = VIR_TRISTATE_BOOL_ABSENT;
2054 virBitmapFree(priv->migrationCaps);
2055 priv->migrationCaps = NULL;
2057 qemuDomainObjResetJob(priv);
2058 qemuDomainObjResetAsyncJob(priv);
2062 static void
2063 qemuDomainObjPrivateFree(void *data)
2065 qemuDomainObjPrivatePtr priv = data;
2067 qemuDomainObjPrivateDataClear(priv);
2069 virObjectUnref(priv->monConfig);
2070 qemuDomainObjFreeJob(priv);
2071 VIR_FREE(priv->lockState);
2072 VIR_FREE(priv->origname);
2074 virChrdevFree(priv->devs);
2076 /* This should never be non-NULL if we get here, but just in case... */
2077 if (priv->mon) {
2078 VIR_ERROR(_("Unexpected QEMU monitor still active during domain deletion"));
2079 qemuMonitorClose(priv->mon);
2081 if (priv->agent) {
2082 VIR_ERROR(_("Unexpected QEMU agent still active during domain deletion"));
2083 qemuAgentClose(priv->agent);
2085 VIR_FREE(priv->cleanupCallbacks);
2087 qemuDomainSecretInfoFree(&priv->migSecinfo);
2088 qemuDomainMasterKeyFree(priv);
2090 VIR_FREE(priv);
2094 static int
2095 qemuStorageSourcePrivateDataAssignSecinfo(qemuDomainSecretInfoPtr *secinfo,
2096 char **alias)
2098 if (!*alias)
2099 return 0;
2101 if (!*secinfo) {
2102 if (VIR_ALLOC(*secinfo) < 0)
2103 return -1;
2105 (*secinfo)->type = VIR_DOMAIN_SECRET_INFO_TYPE_AES;
2108 if ((*secinfo)->type == VIR_DOMAIN_SECRET_INFO_TYPE_AES)
2109 VIR_STEAL_PTR((*secinfo)->s.aes.alias, *alias);
2111 return 0;
2115 static int
2116 qemuStorageSourcePrivateDataParse(xmlXPathContextPtr ctxt,
2117 virStorageSourcePtr src)
2119 qemuDomainStorageSourcePrivatePtr priv;
2120 char *authalias = NULL;
2121 char *encalias = NULL;
2122 int ret = -1;
2124 src->nodestorage = virXPathString("string(./nodenames/nodename[@type='storage']/@name)", ctxt);
2125 src->nodeformat = virXPathString("string(./nodenames/nodename[@type='format']/@name)", ctxt);
2126 src->tlsAlias = virXPathString("string(./objects/TLSx509/@alias)", ctxt);
2128 if (src->pr)
2129 src->pr->mgralias = virXPathString("string(./reservations/@mgralias)", ctxt);
2131 authalias = virXPathString("string(./objects/secret[@type='auth']/@alias)", ctxt);
2132 encalias = virXPathString("string(./objects/secret[@type='encryption']/@alias)", ctxt);
2134 if (authalias || encalias) {
2135 if (!src->privateData &&
2136 !(src->privateData = qemuDomainStorageSourcePrivateNew()))
2137 goto cleanup;
2139 priv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
2141 if (qemuStorageSourcePrivateDataAssignSecinfo(&priv->secinfo, &authalias) < 0)
2142 goto cleanup;
2144 if (qemuStorageSourcePrivateDataAssignSecinfo(&priv->encinfo, &encalias) < 0)
2145 goto cleanup;
2148 if (virStorageSourcePrivateDataParseRelPath(ctxt, src) < 0)
2149 goto cleanup;
2151 ret = 0;
2153 cleanup:
2154 VIR_FREE(authalias);
2155 VIR_FREE(encalias);
2157 return ret;
2161 static void
2162 qemuStorageSourcePrivateDataFormatSecinfo(virBufferPtr buf,
2163 qemuDomainSecretInfoPtr secinfo,
2164 const char *type)
2166 if (!secinfo ||
2167 secinfo->type != VIR_DOMAIN_SECRET_INFO_TYPE_AES ||
2168 !secinfo->s.aes.alias)
2169 return;
2171 virBufferAsprintf(buf, "<secret type='%s' alias='%s'/>\n",
2172 type, secinfo->s.aes.alias);
2176 static int
2177 qemuStorageSourcePrivateDataFormat(virStorageSourcePtr src,
2178 virBufferPtr buf)
2180 VIR_AUTOCLEAN(virBuffer) tmp = VIR_BUFFER_INITIALIZER;
2181 qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
2182 int ret = -1;
2184 if (src->nodestorage || src->nodeformat) {
2185 virBufferAddLit(buf, "<nodenames>\n");
2186 virBufferAdjustIndent(buf, 2);
2187 virBufferEscapeString(buf, "<nodename type='storage' name='%s'/>\n", src->nodestorage);
2188 virBufferEscapeString(buf, "<nodename type='format' name='%s'/>\n", src->nodeformat);
2189 virBufferAdjustIndent(buf, -2);
2190 virBufferAddLit(buf, "</nodenames>\n");
2193 if (src->pr)
2194 virBufferAsprintf(buf, "<reservations mgralias='%s'/>\n", src->pr->mgralias);
2196 if (virStorageSourcePrivateDataFormatRelPath(src, buf) < 0)
2197 goto cleanup;
2199 virBufferSetChildIndent(&tmp, buf);
2201 if (srcPriv) {
2202 qemuStorageSourcePrivateDataFormatSecinfo(&tmp, srcPriv->secinfo, "auth");
2203 qemuStorageSourcePrivateDataFormatSecinfo(&tmp, srcPriv->encinfo, "encryption");
2206 if (src->tlsAlias)
2207 virBufferAsprintf(&tmp, "<TLSx509 alias='%s'/>\n", src->tlsAlias);
2209 if (virXMLFormatElement(buf, "objects", NULL, &tmp) < 0)
2210 goto cleanup;
2212 ret = 0;
2214 cleanup:
2215 return ret;
2219 static int
2220 qemuDomainDiskPrivateParse(xmlXPathContextPtr ctxt,
2221 virDomainDiskDefPtr disk)
2223 qemuDomainDiskPrivatePtr priv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2225 priv->qomName = virXPathString("string(./qom/@name)", ctxt);
2226 priv->nodeCopyOnRead = virXPathString("string(./nodenames/nodename[@type='copyOnRead']/@name)", ctxt);
2228 return 0;
2232 static int
2233 qemuDomainDiskPrivateFormat(virDomainDiskDefPtr disk,
2234 virBufferPtr buf)
2236 qemuDomainDiskPrivatePtr priv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2238 virBufferEscapeString(buf, "<qom name='%s'/>\n", priv->qomName);
2240 if (priv->nodeCopyOnRead) {
2241 virBufferAddLit(buf, "<nodenames>\n");
2242 virBufferAdjustIndent(buf, 2);
2243 virBufferEscapeString(buf, "<nodename type='copyOnRead' name='%s'/>\n",
2244 priv->nodeCopyOnRead);
2245 virBufferAdjustIndent(buf, -2);
2246 virBufferAddLit(buf, "</nodenames>\n");
2249 return 0;
2253 static void
2254 qemuDomainObjPrivateXMLFormatVcpus(virBufferPtr buf,
2255 virDomainDefPtr def)
2257 size_t i;
2258 size_t maxvcpus = virDomainDefGetVcpusMax(def);
2259 virDomainVcpuDefPtr vcpu;
2260 pid_t tid;
2262 virBufferAddLit(buf, "<vcpus>\n");
2263 virBufferAdjustIndent(buf, 2);
2265 for (i = 0; i < maxvcpus; i++) {
2266 vcpu = virDomainDefGetVcpu(def, i);
2267 tid = QEMU_DOMAIN_VCPU_PRIVATE(vcpu)->tid;
2269 if (!vcpu->online || tid == 0)
2270 continue;
2272 virBufferAsprintf(buf, "<vcpu id='%zu' pid='%d'/>\n", i, tid);
2275 virBufferAdjustIndent(buf, -2);
2276 virBufferAddLit(buf, "</vcpus>\n");
2280 static int
2281 qemuDomainObjPrivateXMLFormatAutomaticPlacement(virBufferPtr buf,
2282 qemuDomainObjPrivatePtr priv)
2284 char *nodeset = NULL;
2285 char *cpuset = NULL;
2286 int ret = -1;
2288 if (!priv->autoNodeset && !priv->autoCpuset)
2289 return 0;
2291 if (priv->autoNodeset &&
2292 !((nodeset = virBitmapFormat(priv->autoNodeset))))
2293 goto cleanup;
2295 if (priv->autoCpuset &&
2296 !((cpuset = virBitmapFormat(priv->autoCpuset))))
2297 goto cleanup;
2299 virBufferAddLit(buf, "<numad");
2300 virBufferEscapeString(buf, " nodeset='%s'", nodeset);
2301 virBufferEscapeString(buf, " cpuset='%s'", cpuset);
2302 virBufferAddLit(buf, "/>\n");
2304 ret = 0;
2306 cleanup:
2307 VIR_FREE(nodeset);
2308 VIR_FREE(cpuset);
2309 return ret;
2313 static int
2314 qemuDomainObjPrivateXMLFormatBlockjobs(virBufferPtr buf,
2315 virDomainObjPtr vm)
2317 qemuDomainObjPrivatePtr priv = vm->privateData;
2318 virBuffer attrBuf = VIR_BUFFER_INITIALIZER;
2319 bool bj = qemuDomainHasBlockjob(vm, false);
2320 int ret = -1;
2322 virBufferAsprintf(&attrBuf, " active='%s'",
2323 virTristateBoolTypeToString(virTristateBoolFromBool(bj)));
2325 if (virXMLFormatElement(buf, "blockjobs", &attrBuf, NULL) < 0)
2326 goto cleanup;
2328 /* TODO: merge other blockjobs and backups into uniform space? */
2329 if (priv->backup && virDomainBackupDefFormat(buf, priv->backup, true) < 0)
2330 goto cleanup;
2332 ret = 0;
2333 cleanup:
2334 virBufferFreeAndReset(&attrBuf);
2335 return ret;
2339 void
2340 qemuDomainObjPrivateXMLFormatAllowReboot(virBufferPtr buf,
2341 virTristateBool allowReboot)
2343 virBufferAsprintf(buf, "<allowReboot value='%s'/>\n",
2344 virTristateBoolTypeToString(allowReboot));
2349 static void
2350 qemuDomainObjPrivateXMLFormatPR(virBufferPtr buf,
2351 qemuDomainObjPrivatePtr priv)
2353 if (priv->prDaemonRunning)
2354 virBufferAddLit(buf, "<prDaemon/>\n");
2358 static int
2359 qemuDomainObjPrivateXMLFormatNBDMigrationSource(virBufferPtr buf,
2360 virStorageSourcePtr src)
2362 VIR_AUTOCLEAN(virBuffer) attrBuf = VIR_BUFFER_INITIALIZER;
2363 VIR_AUTOCLEAN(virBuffer) childBuf = VIR_BUFFER_INITIALIZER;
2364 VIR_AUTOCLEAN(virBuffer) privateDataBuf = VIR_BUFFER_INITIALIZER;
2365 int ret = -1;
2367 virBufferSetChildIndent(&childBuf, buf);
2368 virBufferSetChildIndent(&privateDataBuf, &childBuf);
2370 virBufferAsprintf(&attrBuf, " type='%s' format='%s'",
2371 virStorageTypeToString(src->type),
2372 virStorageFileFormatTypeToString(src->format));
2374 if (virDomainStorageSourceFormat(&attrBuf, &childBuf, src,
2375 VIR_DOMAIN_DEF_FORMAT_STATUS, true) < 0)
2376 goto cleanup;
2378 if (qemuStorageSourcePrivateDataFormat(src, &privateDataBuf) < 0)
2379 goto cleanup;
2381 if (virXMLFormatElement(&childBuf, "privateData", NULL, &privateDataBuf) < 0)
2382 goto cleanup;
2384 if (virXMLFormatElement(buf, "migrationSource", &attrBuf, &childBuf) < 0)
2385 goto cleanup;
2387 ret = 0;
2389 cleanup:
2390 return ret;
2394 static int
2395 qemuDomainObjPrivateXMLFormatNBDMigration(virBufferPtr buf,
2396 virDomainObjPtr vm)
2398 VIR_AUTOCLEAN(virBuffer) attrBuf = VIR_BUFFER_INITIALIZER;
2399 VIR_AUTOCLEAN(virBuffer) childBuf = VIR_BUFFER_INITIALIZER;
2400 size_t i;
2401 virDomainDiskDefPtr disk;
2402 qemuDomainDiskPrivatePtr diskPriv;
2403 int ret = -1;
2405 for (i = 0; i < vm->def->ndisks; i++) {
2406 disk = vm->def->disks[i];
2407 diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2409 virBufferSetChildIndent(&childBuf, buf);
2411 virBufferAsprintf(&attrBuf, " dev='%s' migrating='%s'",
2412 disk->dst, diskPriv->migrating ? "yes" : "no");
2414 if (diskPriv->migrSource &&
2415 qemuDomainObjPrivateXMLFormatNBDMigrationSource(&childBuf,
2416 diskPriv->migrSource) < 0)
2417 goto cleanup;
2419 if (virXMLFormatElement(buf, "disk", &attrBuf, &childBuf) < 0)
2420 goto cleanup;
2423 ret = 0;
2425 cleanup:
2426 return ret;
2430 static int
2431 qemuDomainObjPrivateXMLFormatJob(virBufferPtr buf,
2432 virDomainObjPtr vm,
2433 qemuDomainObjPrivatePtr priv)
2435 VIR_AUTOCLEAN(virBuffer) attrBuf = VIR_BUFFER_INITIALIZER;
2436 VIR_AUTOCLEAN(virBuffer) childBuf = VIR_BUFFER_INITIALIZER;
2437 qemuDomainJob job = priv->job.active;
2438 int ret = -1;
2440 if (!qemuDomainTrackJob(job))
2441 job = QEMU_JOB_NONE;
2443 if (job == QEMU_JOB_NONE &&
2444 priv->job.asyncJob == QEMU_ASYNC_JOB_NONE)
2445 return 0;
2447 virBufferSetChildIndent(&childBuf, buf);
2449 virBufferAsprintf(&attrBuf, " type='%s' async='%s'",
2450 qemuDomainJobTypeToString(job),
2451 qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
2453 if (priv->job.phase) {
2454 virBufferAsprintf(&attrBuf, " phase='%s'",
2455 qemuDomainAsyncJobPhaseToString(priv->job.asyncJob,
2456 priv->job.phase));
2459 if (priv->job.asyncJob != QEMU_ASYNC_JOB_NONE)
2460 virBufferAsprintf(&attrBuf, " flags='0x%lx'", priv->job.apiFlags);
2462 if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT &&
2463 qemuDomainObjPrivateXMLFormatNBDMigration(&childBuf, vm) < 0)
2464 goto cleanup;
2466 if (priv->job.migParams)
2467 qemuMigrationParamsFormat(&childBuf, priv->job.migParams);
2469 if (virXMLFormatElement(buf, "job", &attrBuf, &childBuf) < 0)
2470 goto cleanup;
2472 ret = 0;
2474 cleanup:
2475 return ret;
2479 static int
2480 qemuDomainObjPrivateXMLFormat(virBufferPtr buf,
2481 virDomainObjPtr vm)
2483 qemuDomainObjPrivatePtr priv = vm->privateData;
2484 const char *monitorpath;
2486 /* priv->monitor_chr is set only for qemu */
2487 if (priv->monConfig) {
2488 switch (priv->monConfig->type) {
2489 case VIR_DOMAIN_CHR_TYPE_UNIX:
2490 monitorpath = priv->monConfig->data.nix.path;
2491 break;
2492 default:
2493 case VIR_DOMAIN_CHR_TYPE_PTY:
2494 monitorpath = priv->monConfig->data.file.path;
2495 break;
2498 virBufferEscapeString(buf, "<monitor path='%s'", monitorpath);
2499 if (priv->monJSON)
2500 virBufferAddLit(buf, " json='1'");
2501 virBufferAsprintf(buf, " type='%s'/>\n",
2502 virDomainChrTypeToString(priv->monConfig->type));
2505 if (priv->namespaces) {
2506 ssize_t ns = -1;
2508 virBufferAddLit(buf, "<namespaces>\n");
2509 virBufferAdjustIndent(buf, 2);
2510 while ((ns = virBitmapNextSetBit(priv->namespaces, ns)) >= 0)
2511 virBufferAsprintf(buf, "<%s/>\n", qemuDomainNamespaceTypeToString(ns));
2512 virBufferAdjustIndent(buf, -2);
2513 virBufferAddLit(buf, "</namespaces>\n");
2516 qemuDomainObjPrivateXMLFormatVcpus(buf, vm->def);
2518 if (priv->qemuCaps) {
2519 size_t i;
2520 virBufferAddLit(buf, "<qemuCaps>\n");
2521 virBufferAdjustIndent(buf, 2);
2522 for (i = 0; i < QEMU_CAPS_LAST; i++) {
2523 if (virQEMUCapsGet(priv->qemuCaps, i)) {
2524 virBufferAsprintf(buf, "<flag name='%s'/>\n",
2525 virQEMUCapsTypeToString(i));
2528 virBufferAdjustIndent(buf, -2);
2529 virBufferAddLit(buf, "</qemuCaps>\n");
2532 if (priv->lockState)
2533 virBufferAsprintf(buf, "<lockstate>%s</lockstate>\n", priv->lockState);
2535 if (qemuDomainObjPrivateXMLFormatJob(buf, vm, priv) < 0)
2536 return -1;
2538 if (priv->fakeReboot)
2539 virBufferAddLit(buf, "<fakereboot/>\n");
2541 if (priv->qemuDevices && *priv->qemuDevices) {
2542 char **tmp = priv->qemuDevices;
2543 virBufferAddLit(buf, "<devices>\n");
2544 virBufferAdjustIndent(buf, 2);
2545 while (*tmp) {
2546 virBufferAsprintf(buf, "<device alias='%s'/>\n", *tmp);
2547 tmp++;
2549 virBufferAdjustIndent(buf, -2);
2550 virBufferAddLit(buf, "</devices>\n");
2553 if (qemuDomainObjPrivateXMLFormatAutomaticPlacement(buf, priv) < 0)
2554 return -1;
2556 /* Various per-domain paths */
2557 virBufferEscapeString(buf, "<libDir path='%s'/>\n", priv->libDir);
2558 virBufferEscapeString(buf, "<channelTargetDir path='%s'/>\n",
2559 priv->channelTargetDir);
2561 virCPUDefFormatBufFull(buf, priv->origCPU, NULL);
2563 if (priv->chardevStdioLogd)
2564 virBufferAddLit(buf, "<chardevStdioLogd/>\n");
2566 if (priv->rememberOwner)
2567 virBufferAddLit(buf, "<rememberOwner/>\n");
2569 qemuDomainObjPrivateXMLFormatAllowReboot(buf, priv->allowReboot);
2571 qemuDomainObjPrivateXMLFormatPR(buf, priv);
2573 if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV))
2574 virBufferAsprintf(buf, "<nodename index='%llu'/>\n", priv->nodenameindex);
2576 if (priv->memPrealloc)
2577 virBufferAddLit(buf, "<memPrealloc/>\n");
2579 if (qemuDomainObjPrivateXMLFormatBlockjobs(buf, vm) < 0)
2580 return -1;
2582 return 0;
2586 static int
2587 qemuDomainObjPrivateXMLParseVcpu(xmlNodePtr node,
2588 unsigned int idx,
2589 virDomainDefPtr def)
2591 virDomainVcpuDefPtr vcpu;
2592 char *idstr;
2593 char *pidstr;
2594 unsigned int tmp;
2595 int ret = -1;
2597 idstr = virXMLPropString(node, "id");
2599 if (idstr &&
2600 (virStrToLong_uip(idstr, NULL, 10, &idx) < 0)) {
2601 virReportError(VIR_ERR_INTERNAL_ERROR,
2602 _("cannot parse vcpu index '%s'"), idstr);
2603 goto cleanup;
2605 if (!(vcpu = virDomainDefGetVcpu(def, idx))) {
2606 virReportError(VIR_ERR_INTERNAL_ERROR,
2607 _("invalid vcpu index '%u'"), idx);
2608 goto cleanup;
2611 if (!(pidstr = virXMLPropString(node, "pid")))
2612 goto cleanup;
2614 if (virStrToLong_uip(pidstr, NULL, 10, &tmp) < 0)
2615 goto cleanup;
2617 QEMU_DOMAIN_VCPU_PRIVATE(vcpu)->tid = tmp;
2619 ret = 0;
2621 cleanup:
2622 VIR_FREE(idstr);
2623 VIR_FREE(pidstr);
2624 return ret;
2628 static int
2629 qemuDomainObjPrivateXMLParseAutomaticPlacement(xmlXPathContextPtr ctxt,
2630 qemuDomainObjPrivatePtr priv,
2631 virQEMUDriverPtr driver)
2633 virCapsPtr caps = NULL;
2634 char *nodeset;
2635 char *cpuset;
2636 int nodesetSize = 0;
2637 size_t i;
2638 int ret = -1;
2640 nodeset = virXPathString("string(./numad/@nodeset)", ctxt);
2641 cpuset = virXPathString("string(./numad/@cpuset)", ctxt);
2643 if (!nodeset && !cpuset)
2644 return 0;
2646 if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
2647 goto cleanup;
2649 /* Figure out how big the nodeset bitmap needs to be.
2650 * This is necessary because NUMA node IDs are not guaranteed to
2651 * start from 0 or be densely allocated */
2652 for (i = 0; i < caps->host.nnumaCell; i++)
2653 nodesetSize = MAX(nodesetSize, caps->host.numaCell[i]->num + 1);
2655 if (nodeset &&
2656 virBitmapParse(nodeset, &priv->autoNodeset, nodesetSize) < 0)
2657 goto cleanup;
2659 if (cpuset) {
2660 if (virBitmapParse(cpuset, &priv->autoCpuset, VIR_DOMAIN_CPUMASK_LEN) < 0)
2661 goto cleanup;
2662 } else {
2663 /* autoNodeset is present in this case, since otherwise we wouldn't
2664 * reach this code */
2665 if (!(priv->autoCpuset = virCapabilitiesGetCpusForNodemask(caps,
2666 priv->autoNodeset)))
2667 goto cleanup;
2670 ret = 0;
2672 cleanup:
2673 virObjectUnref(caps);
2674 VIR_FREE(nodeset);
2675 VIR_FREE(cpuset);
2677 return ret;
2681 static int
2682 qemuDomainObjPrivateXMLParseBlockjobs(virQEMUDriverPtr driver,
2683 qemuDomainObjPrivatePtr priv,
2684 xmlXPathContextPtr ctxt)
2686 xmlNodePtr node;
2687 char *active;
2688 int tmp;
2689 int ret = -1;
2690 size_t i;
2692 if ((active = virXPathString("string(./blockjobs/@active)", ctxt)) &&
2693 (tmp = virTristateBoolTypeFromString(active)) > 0)
2694 priv->reconnectBlockjobs = tmp;
2696 if ((node = virXPathNode("./domainbackup", ctxt))) {
2697 if (!(priv->backup = virDomainBackupDefParseNode(ctxt->doc, node,
2698 driver->xmlopt,
2699 VIR_DOMAIN_BACKUP_PARSE_INTERNAL)))
2700 goto cleanup;
2701 /* The backup job is only stored in XML if backupBegin
2702 * succeeded at exporting the disk, so no need to store disk
2703 * state when we can just force-reset it to a known-good
2704 * value. */
2705 for (i = 0; i < priv->backup->ndisks; i++)
2706 priv->backup->disks[i].state = VIR_DOMAIN_BACKUP_DISK_STATE_EXPORT;
2709 ret = 0;
2710 cleanup:
2711 VIR_FREE(active);
2712 return ret;
2717 qemuDomainObjPrivateXMLParseAllowReboot(xmlXPathContextPtr ctxt,
2718 virTristateBool *allowReboot)
2720 int ret = -1;
2721 int val;
2722 char *valStr;
2724 if ((valStr = virXPathString("string(./allowReboot/@value)", ctxt))) {
2725 if ((val = virTristateBoolTypeFromString(valStr)) < 0) {
2726 virReportError(VIR_ERR_INTERNAL_ERROR,
2727 _("invalid allowReboot value '%s'"), valStr);
2728 goto cleanup;
2730 *allowReboot = val;
2733 ret = 0;
2735 cleanup:
2736 VIR_FREE(valStr);
2737 return ret;
2741 static void
2742 qemuDomainObjPrivateXMLParsePR(xmlXPathContextPtr ctxt,
2743 bool *prDaemonRunning)
2745 *prDaemonRunning = virXPathBoolean("boolean(./prDaemon)", ctxt) > 0;
2749 static int
2750 qemuDomainObjPrivateXMLParseJobNBDSource(xmlNodePtr node,
2751 xmlXPathContextPtr ctxt,
2752 virDomainDiskDefPtr disk)
2754 VIR_XPATH_NODE_AUTORESTORE(ctxt);
2755 qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2756 char *format = NULL;
2757 char *type = NULL;
2758 int ret = -1;
2759 VIR_AUTOUNREF(virStorageSourcePtr) migrSource = NULL;
2761 ctxt->node = node;
2763 if (!(ctxt->node = virXPathNode("./migrationSource", ctxt))) {
2764 ret = 0;
2765 goto cleanup;
2768 if (!(migrSource = virStorageSourceNew()))
2769 goto cleanup;
2771 if (!(type = virXMLPropString(ctxt->node, "type"))) {
2772 virReportError(VIR_ERR_XML_ERROR, "%s",
2773 _("missing storage source type"));
2774 goto cleanup;
2777 if (!(format = virXMLPropString(ctxt->node, "format"))) {
2778 virReportError(VIR_ERR_XML_ERROR, "%s",
2779 _("missing storage source format"));
2780 goto cleanup;
2783 if ((migrSource->type = virStorageTypeFromString(type)) <= 0) {
2784 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2785 _("unknown storage source type '%s'"), type);
2786 goto cleanup;
2789 if ((migrSource->format = virStorageFileFormatTypeFromString(format)) <= 0) {
2790 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2791 _("unknown storage source format '%s'"), format);
2792 goto cleanup;
2795 if (virDomainStorageSourceParse(ctxt->node, ctxt, migrSource,
2796 VIR_DOMAIN_DEF_PARSE_STATUS, NULL) < 0)
2797 goto cleanup;
2799 if ((ctxt->node = virXPathNode("./privateData", ctxt)) &&
2800 qemuStorageSourcePrivateDataParse(ctxt, migrSource) < 0)
2801 goto cleanup;
2803 VIR_STEAL_PTR(diskPriv->migrSource, migrSource);
2804 ret = 0;
2806 cleanup:
2807 VIR_FREE(format);
2808 VIR_FREE(type);
2809 return ret;
2813 static int
2814 qemuDomainObjPrivateXMLParseJobNBD(virDomainObjPtr vm,
2815 qemuDomainObjPrivatePtr priv,
2816 xmlXPathContextPtr ctxt)
2818 xmlNodePtr *nodes = NULL;
2819 char *dst = NULL;
2820 size_t i;
2821 int n;
2822 int ret = -1;
2824 if ((n = virXPathNodeSet("./disk[@migrating='yes']", ctxt, &nodes)) < 0)
2825 goto cleanup;
2827 if (n > 0) {
2828 if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
2829 VIR_WARN("Found disks marked for migration but we were not "
2830 "migrating");
2831 n = 0;
2833 for (i = 0; i < n; i++) {
2834 virDomainDiskDefPtr disk;
2836 if ((dst = virXMLPropString(nodes[i], "dev")) &&
2837 (disk = virDomainDiskByName(vm->def, dst, false))) {
2838 QEMU_DOMAIN_DISK_PRIVATE(disk)->migrating = true;
2840 if (qemuDomainObjPrivateXMLParseJobNBDSource(nodes[i], ctxt,
2841 disk) < 0)
2842 goto cleanup;
2845 VIR_FREE(dst);
2849 ret = 0;
2851 cleanup:
2852 VIR_FREE(nodes);
2853 VIR_FREE(dst);
2854 return ret;
2858 static int
2859 qemuDomainObjPrivateXMLParseJob(virDomainObjPtr vm,
2860 qemuDomainObjPrivatePtr priv,
2861 xmlXPathContextPtr ctxt)
2863 VIR_XPATH_NODE_AUTORESTORE(ctxt);
2864 char *tmp = NULL;
2865 int ret = -1;
2867 if (!(ctxt->node = virXPathNode("./job[1]", ctxt))) {
2868 ret = 0;
2869 goto cleanup;
2872 if ((tmp = virXPathString("string(@type)", ctxt))) {
2873 int type;
2875 if ((type = qemuDomainJobTypeFromString(tmp)) < 0) {
2876 virReportError(VIR_ERR_INTERNAL_ERROR,
2877 _("Unknown job type %s"), tmp);
2878 goto cleanup;
2880 VIR_FREE(tmp);
2881 priv->job.active = type;
2884 if ((tmp = virXPathString("string(@async)", ctxt))) {
2885 int async;
2887 if ((async = qemuDomainAsyncJobTypeFromString(tmp)) < 0) {
2888 virReportError(VIR_ERR_INTERNAL_ERROR,
2889 _("Unknown async job type %s"), tmp);
2890 goto cleanup;
2892 VIR_FREE(tmp);
2893 priv->job.asyncJob = async;
2895 if ((tmp = virXPathString("string(@phase)", ctxt))) {
2896 priv->job.phase = qemuDomainAsyncJobPhaseFromString(async, tmp);
2897 if (priv->job.phase < 0) {
2898 virReportError(VIR_ERR_INTERNAL_ERROR,
2899 _("Unknown job phase %s"), tmp);
2900 goto cleanup;
2902 VIR_FREE(tmp);
2906 if (virXPathULongHex("string(@flags)", ctxt, &priv->job.apiFlags) == -2) {
2907 virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid job flags"));
2908 goto cleanup;
2911 if (qemuDomainObjPrivateXMLParseJobNBD(vm, priv, ctxt) < 0)
2912 goto cleanup;
2914 if (qemuMigrationParamsParse(ctxt, &priv->job.migParams) < 0)
2915 goto cleanup;
2917 ret = 0;
2919 cleanup:
2920 VIR_FREE(tmp);
2921 return ret;
2925 static int
2926 qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt,
2927 virDomainObjPtr vm,
2928 virDomainDefParserConfigPtr config)
2930 qemuDomainObjPrivatePtr priv = vm->privateData;
2931 virQEMUDriverPtr driver = config->priv;
2932 char *monitorpath;
2933 char *tmp = NULL;
2934 int n;
2935 size_t i;
2936 xmlNodePtr *nodes = NULL;
2937 xmlNodePtr node = NULL;
2938 virQEMUCapsPtr qemuCaps = NULL;
2940 if (!(priv->monConfig = virDomainChrSourceDefNew(NULL)))
2941 goto error;
2943 if (!(monitorpath =
2944 virXPathString("string(./monitor[1]/@path)", ctxt))) {
2945 virReportError(VIR_ERR_INTERNAL_ERROR,
2946 "%s", _("no monitor path"));
2947 goto error;
2950 tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
2951 if (tmp)
2952 priv->monConfig->type = virDomainChrTypeFromString(tmp);
2953 else
2954 priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
2955 VIR_FREE(tmp);
2957 priv->monJSON = virXPathBoolean("count(./monitor[@json = '1']) > 0",
2958 ctxt) > 0;
2960 switch (priv->monConfig->type) {
2961 case VIR_DOMAIN_CHR_TYPE_PTY:
2962 priv->monConfig->data.file.path = monitorpath;
2963 break;
2964 case VIR_DOMAIN_CHR_TYPE_UNIX:
2965 priv->monConfig->data.nix.path = monitorpath;
2966 break;
2967 default:
2968 VIR_FREE(monitorpath);
2969 virReportError(VIR_ERR_INTERNAL_ERROR,
2970 _("unsupported monitor type '%s'"),
2971 virDomainChrTypeToString(priv->monConfig->type));
2972 goto error;
2975 if ((node = virXPathNode("./namespaces", ctxt))) {
2976 xmlNodePtr next;
2978 for (next = node->children; next; next = next->next) {
2979 int ns = qemuDomainNamespaceTypeFromString((const char *)next->name);
2981 if (ns < 0) {
2982 virReportError(VIR_ERR_INTERNAL_ERROR,
2983 _("malformed namespace name: %s"),
2984 next->name);
2985 goto error;
2988 if (qemuDomainEnableNamespace(vm, ns) < 0)
2989 goto error;
2993 if (priv->namespaces &&
2994 virBitmapIsAllClear(priv->namespaces)) {
2995 virBitmapFree(priv->namespaces);
2996 priv->namespaces = NULL;
2999 priv->rememberOwner = virXPathBoolean("count(./rememberOwner) > 0", ctxt);
3001 if ((n = virXPathNodeSet("./vcpus/vcpu", ctxt, &nodes)) < 0)
3002 goto error;
3004 for (i = 0; i < n; i++) {
3005 if (qemuDomainObjPrivateXMLParseVcpu(nodes[i], i, vm->def) < 0)
3006 goto error;
3008 VIR_FREE(nodes);
3010 if ((n = virXPathNodeSet("./qemuCaps/flag", ctxt, &nodes)) < 0) {
3011 virReportError(VIR_ERR_INTERNAL_ERROR,
3012 "%s", _("failed to parse qemu capabilities flags"));
3013 goto error;
3015 if (n > 0) {
3016 if (!(qemuCaps = virQEMUCapsNew()))
3017 goto error;
3019 for (i = 0; i < n; i++) {
3020 char *str = virXMLPropString(nodes[i], "name");
3021 if (str) {
3022 int flag = virQEMUCapsTypeFromString(str);
3023 if (flag < 0) {
3024 virReportError(VIR_ERR_INTERNAL_ERROR,
3025 _("Unknown qemu capabilities flag %s"), str);
3026 VIR_FREE(str);
3027 goto error;
3029 VIR_FREE(str);
3030 virQEMUCapsSet(qemuCaps, flag);
3034 VIR_STEAL_PTR(priv->qemuCaps, qemuCaps);
3036 VIR_FREE(nodes);
3038 priv->lockState = virXPathString("string(./lockstate)", ctxt);
3040 if (qemuDomainObjPrivateXMLParseJob(vm, priv, ctxt) < 0)
3041 goto error;
3043 priv->fakeReboot = virXPathBoolean("boolean(./fakereboot)", ctxt) == 1;
3045 if ((n = virXPathNodeSet("./devices/device", ctxt, &nodes)) < 0) {
3046 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3047 _("failed to parse qemu device list"));
3048 goto error;
3050 if (n > 0) {
3051 /* NULL-terminated list */
3052 if (VIR_ALLOC_N(priv->qemuDevices, n + 1) < 0)
3053 goto error;
3055 for (i = 0; i < n; i++) {
3056 priv->qemuDevices[i] = virXMLPropString(nodes[i], "alias");
3057 if (!priv->qemuDevices[i]) {
3058 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3059 _("failed to parse qemu device list"));
3060 goto error;
3064 VIR_FREE(nodes);
3066 if (qemuDomainObjPrivateXMLParseAutomaticPlacement(ctxt, priv, driver) < 0)
3067 goto error;
3069 if ((tmp = virXPathString("string(./libDir/@path)", ctxt)))
3070 priv->libDir = tmp;
3071 if ((tmp = virXPathString("string(./channelTargetDir/@path)", ctxt)))
3072 priv->channelTargetDir = tmp;
3073 tmp = NULL;
3075 if (qemuDomainSetPrivatePathsOld(driver, vm) < 0)
3076 goto error;
3078 if (virCPUDefParseXML(ctxt, "./cpu", VIR_CPU_TYPE_GUEST, &priv->origCPU) < 0)
3079 goto error;
3081 priv->chardevStdioLogd = virXPathBoolean("boolean(./chardevStdioLogd)",
3082 ctxt) == 1;
3084 qemuDomainObjPrivateXMLParseAllowReboot(ctxt, &priv->allowReboot);
3086 qemuDomainObjPrivateXMLParsePR(ctxt, &priv->prDaemonRunning);
3088 if (qemuDomainObjPrivateXMLParseBlockjobs(driver, priv, ctxt) < 0)
3089 goto error;
3091 qemuDomainStorageIdReset(priv);
3092 if (virXPathULongLong("string(./nodename/@index)", ctxt,
3093 &priv->nodenameindex) == -2) {
3094 virReportError(VIR_ERR_XML_ERROR, "%s",
3095 _("failed to parse node name index"));
3096 goto error;
3099 priv->memPrealloc = virXPathBoolean("boolean(./memPrealloc)", ctxt) == 1;
3101 return 0;
3103 error:
3104 VIR_FREE(nodes);
3105 VIR_FREE(tmp);
3106 virBitmapFree(priv->namespaces);
3107 priv->namespaces = NULL;
3108 virObjectUnref(priv->monConfig);
3109 priv->monConfig = NULL;
3110 virStringListFree(priv->qemuDevices);
3111 priv->qemuDevices = NULL;
3112 virObjectUnref(qemuCaps);
3113 return -1;
3117 static void *
3118 qemuDomainObjPrivateXMLGetParseOpaque(virDomainObjPtr vm)
3120 qemuDomainObjPrivatePtr priv = vm->privateData;
3122 return priv->qemuCaps;
3126 virDomainXMLPrivateDataCallbacks virQEMUDriverPrivateDataCallbacks = {
3127 .alloc = qemuDomainObjPrivateAlloc,
3128 .free = qemuDomainObjPrivateFree,
3129 .diskNew = qemuDomainDiskPrivateNew,
3130 .diskParse = qemuDomainDiskPrivateParse,
3131 .diskFormat = qemuDomainDiskPrivateFormat,
3132 .vcpuNew = qemuDomainVcpuPrivateNew,
3133 .chrSourceNew = qemuDomainChrSourcePrivateNew,
3134 .vsockNew = qemuDomainVsockPrivateNew,
3135 .graphicsNew = qemuDomainGraphicsPrivateNew,
3136 .parse = qemuDomainObjPrivateXMLParse,
3137 .format = qemuDomainObjPrivateXMLFormat,
3138 .getParseOpaque = qemuDomainObjPrivateXMLGetParseOpaque,
3139 .storageParse = qemuStorageSourcePrivateDataParse,
3140 .storageFormat = qemuStorageSourcePrivateDataFormat,
3144 static void
3145 qemuDomainDefNamespaceFree(void *nsdata)
3147 qemuDomainCmdlineDefPtr cmd = nsdata;
3149 qemuDomainCmdlineDefFree(cmd);
3152 static int
3153 qemuDomainDefNamespaceParse(xmlDocPtr xml ATTRIBUTE_UNUSED,
3154 xmlNodePtr root ATTRIBUTE_UNUSED,
3155 xmlXPathContextPtr ctxt,
3156 void **data)
3158 qemuDomainCmdlineDefPtr cmd = NULL;
3159 bool uses_qemu_ns = false;
3160 xmlNodePtr *nodes = NULL;
3161 int n;
3162 size_t i;
3164 if (xmlXPathRegisterNs(ctxt, BAD_CAST "qemu", BAD_CAST QEMU_NAMESPACE_HREF) < 0) {
3165 virReportError(VIR_ERR_INTERNAL_ERROR,
3166 _("Failed to register xml namespace '%s'"),
3167 QEMU_NAMESPACE_HREF);
3168 return -1;
3171 if (VIR_ALLOC(cmd) < 0)
3172 return -1;
3174 /* first handle the extra command-line arguments */
3175 n = virXPathNodeSet("./qemu:commandline/qemu:arg", ctxt, &nodes);
3176 if (n < 0)
3177 goto error;
3178 uses_qemu_ns |= n > 0;
3180 if (n && VIR_ALLOC_N(cmd->args, n) < 0)
3181 goto error;
3183 for (i = 0; i < n; i++) {
3184 cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
3185 if (cmd->args[cmd->num_args] == NULL) {
3186 virReportError(VIR_ERR_INTERNAL_ERROR,
3187 "%s", _("No qemu command-line argument specified"));
3188 goto error;
3190 cmd->num_args++;
3193 VIR_FREE(nodes);
3195 /* now handle the extra environment variables */
3196 n = virXPathNodeSet("./qemu:commandline/qemu:env", ctxt, &nodes);
3197 if (n < 0)
3198 goto error;
3199 uses_qemu_ns |= n > 0;
3201 if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
3202 goto error;
3204 if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
3205 goto error;
3207 for (i = 0; i < n; i++) {
3208 char *tmp;
3210 tmp = virXMLPropString(nodes[i], "name");
3211 if (tmp == NULL) {
3212 virReportError(VIR_ERR_INTERNAL_ERROR,
3213 "%s", _("No qemu environment name specified"));
3214 goto error;
3216 if (tmp[0] == '\0') {
3217 virReportError(VIR_ERR_INTERNAL_ERROR,
3218 "%s", _("Empty qemu environment name specified"));
3219 goto error;
3221 if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
3222 virReportError(VIR_ERR_INTERNAL_ERROR,
3223 "%s", _("Invalid environment name, it must begin with a letter or underscore"));
3224 goto error;
3226 if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
3227 virReportError(VIR_ERR_INTERNAL_ERROR,
3228 "%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
3229 goto error;
3232 cmd->env_name[cmd->num_env] = tmp;
3234 cmd->env_value[cmd->num_env] = virXMLPropString(nodes[i], "value");
3235 /* a NULL value for command is allowed, since it might be empty */
3236 cmd->num_env++;
3239 VIR_FREE(nodes);
3241 if (uses_qemu_ns)
3242 *data = cmd;
3243 else
3244 VIR_FREE(cmd);
3246 return 0;
3248 error:
3249 VIR_FREE(nodes);
3250 qemuDomainDefNamespaceFree(cmd);
3251 return -1;
3254 static int
3255 qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
3256 void *nsdata)
3258 qemuDomainCmdlineDefPtr cmd = nsdata;
3259 size_t i;
3261 if (!cmd->num_args && !cmd->num_env)
3262 return 0;
3264 virBufferAddLit(buf, "<qemu:commandline>\n");
3265 virBufferAdjustIndent(buf, 2);
3267 for (i = 0; i < cmd->num_args; i++)
3268 virBufferEscapeString(buf, "<qemu:arg value='%s'/>\n",
3269 cmd->args[i]);
3270 for (i = 0; i < cmd->num_env; i++) {
3271 virBufferAsprintf(buf, "<qemu:env name='%s'", cmd->env_name[i]);
3272 if (cmd->env_value[i])
3273 virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
3274 virBufferAddLit(buf, "/>\n");
3277 virBufferAdjustIndent(buf, -2);
3278 virBufferAddLit(buf, "</qemu:commandline>\n");
3279 return 0;
3282 static const char *
3283 qemuDomainDefNamespaceHref(void)
3285 return "xmlns:qemu='" QEMU_NAMESPACE_HREF "'";
3289 virDomainXMLNamespace virQEMUDriverDomainXMLNamespace = {
3290 .parse = qemuDomainDefNamespaceParse,
3291 .free = qemuDomainDefNamespaceFree,
3292 .format = qemuDomainDefNamespaceFormatXML,
3293 .href = qemuDomainDefNamespaceHref,
3297 static int
3298 qemuDomainDefAddImplicitInputDevice(virDomainDef *def)
3300 if (ARCH_IS_X86(def->os.arch)) {
3301 if (virDomainDefMaybeAddInput(def,
3302 VIR_DOMAIN_INPUT_TYPE_MOUSE,
3303 VIR_DOMAIN_INPUT_BUS_PS2) < 0)
3304 return -1;
3306 if (virDomainDefMaybeAddInput(def,
3307 VIR_DOMAIN_INPUT_TYPE_KBD,
3308 VIR_DOMAIN_INPUT_BUS_PS2) < 0)
3309 return -1;
3312 return 0;
3316 static int
3317 qemuDomainDefAddDefaultDevices(virDomainDefPtr def,
3318 virQEMUCapsPtr qemuCaps)
3320 bool addDefaultUSB = true;
3321 int usbModel = -1; /* "default for machinetype" */
3322 int pciRoot; /* index within def->controllers */
3323 bool addImplicitSATA = false;
3324 bool addPCIRoot = false;
3325 bool addPCIeRoot = false;
3326 bool addDefaultMemballoon = true;
3327 bool addDefaultUSBKBD = false;
3328 bool addDefaultUSBMouse = false;
3329 bool addPanicDevice = false;
3330 int ret = -1;
3332 /* add implicit input devices */
3333 if (qemuDomainDefAddImplicitInputDevice(def) < 0)
3334 goto cleanup;
3336 /* Add implicit PCI root controller if the machine has one */
3337 switch (def->os.arch) {
3338 case VIR_ARCH_I686:
3339 case VIR_ARCH_X86_64:
3340 if (STREQ(def->os.machine, "isapc")) {
3341 addDefaultUSB = false;
3342 break;
3344 if (qemuDomainIsQ35(def)) {
3345 addPCIeRoot = true;
3346 addImplicitSATA = true;
3348 /* Prefer adding a USB3 controller if supported, fall back
3349 * to USB2 if there is no USB3 available, and if that's
3350 * unavailable don't add anything.
3352 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_QEMU_XHCI))
3353 usbModel = VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI;
3354 else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NEC_USB_XHCI))
3355 usbModel = VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI;
3356 else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_ICH9_USB_EHCI1))
3357 usbModel = VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1;
3358 else
3359 addDefaultUSB = false;
3360 break;
3362 if (qemuDomainIsI440FX(def))
3363 addPCIRoot = true;
3364 break;
3366 case VIR_ARCH_ARMV6L:
3367 addDefaultUSB = false;
3368 addDefaultMemballoon = false;
3369 if (STREQ(def->os.machine, "versatilepb"))
3370 addPCIRoot = true;
3371 break;
3373 case VIR_ARCH_ARMV7L:
3374 case VIR_ARCH_AARCH64:
3375 addDefaultUSB = false;
3376 addDefaultMemballoon = false;
3377 if (qemuDomainIsARMVirt(def))
3378 addPCIeRoot = virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_GPEX);
3379 break;
3381 case VIR_ARCH_PPC64:
3382 case VIR_ARCH_PPC64LE:
3383 addPCIRoot = true;
3384 addDefaultUSBKBD = true;
3385 addDefaultUSBMouse = true;
3386 /* For pSeries guests, the firmware provides the same
3387 * functionality as the pvpanic device, so automatically
3388 * add the definition if not already present */
3389 if (qemuDomainIsPSeries(def))
3390 addPanicDevice = true;
3391 break;
3393 case VIR_ARCH_ALPHA:
3394 case VIR_ARCH_PPC:
3395 case VIR_ARCH_PPCEMB:
3396 case VIR_ARCH_SH4:
3397 case VIR_ARCH_SH4EB:
3398 addPCIRoot = true;
3399 break;
3401 case VIR_ARCH_RISCV32:
3402 case VIR_ARCH_RISCV64:
3403 addDefaultUSB = false;
3404 if (qemuDomainIsRISCVVirt(def))
3405 addPCIeRoot = virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_GPEX);
3406 break;
3408 case VIR_ARCH_S390:
3409 case VIR_ARCH_S390X:
3410 addDefaultUSB = false;
3411 addPanicDevice = true;
3412 addPCIRoot = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_ZPCI);
3413 break;
3415 case VIR_ARCH_SPARC:
3416 case VIR_ARCH_SPARC64:
3417 addPCIRoot = true;
3418 break;
3420 case VIR_ARCH_ARMV7B:
3421 case VIR_ARCH_CRIS:
3422 case VIR_ARCH_ITANIUM:
3423 case VIR_ARCH_LM32:
3424 case VIR_ARCH_M68K:
3425 case VIR_ARCH_MICROBLAZE:
3426 case VIR_ARCH_MICROBLAZEEL:
3427 case VIR_ARCH_MIPS:
3428 case VIR_ARCH_MIPSEL:
3429 case VIR_ARCH_MIPS64:
3430 case VIR_ARCH_MIPS64EL:
3431 case VIR_ARCH_OR32:
3432 case VIR_ARCH_PARISC:
3433 case VIR_ARCH_PARISC64:
3434 case VIR_ARCH_PPCLE:
3435 case VIR_ARCH_UNICORE32:
3436 case VIR_ARCH_XTENSA:
3437 case VIR_ARCH_XTENSAEB:
3438 case VIR_ARCH_NONE:
3439 case VIR_ARCH_LAST:
3440 default:
3441 break;
3444 if (addDefaultUSB &&
3445 virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_USB, 0) < 0 &&
3446 virDomainDefAddUSBController(def, 0, usbModel) < 0)
3447 goto cleanup;
3449 if (addImplicitSATA &&
3450 virDomainDefMaybeAddController(
3451 def, VIR_DOMAIN_CONTROLLER_TYPE_SATA, 0, -1) < 0)
3452 goto cleanup;
3454 pciRoot = virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0);
3456 /* NB: any machine that sets addPCIRoot to true must also return
3457 * true from the function qemuDomainSupportsPCI().
3459 if (addPCIRoot) {
3460 if (pciRoot >= 0) {
3461 if (def->controllers[pciRoot]->model != VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) {
3462 virReportError(VIR_ERR_XML_ERROR,
3463 _("The PCI controller with index='0' must be "
3464 "model='pci-root' for this machine type, "
3465 "but model='%s' was found instead"),
3466 virDomainControllerModelPCITypeToString(def->controllers[pciRoot]->model));
3467 goto cleanup;
3469 } else if (!virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
3470 VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT)) {
3471 goto cleanup;
3475 /* When a machine has a pcie-root, make sure that there is always
3476 * a dmi-to-pci-bridge controller added as bus 1, and a pci-bridge
3477 * as bus 2, so that standard PCI devices can be connected
3479 * NB: any machine that sets addPCIeRoot to true must also return
3480 * true from the function qemuDomainSupportsPCI().
3482 if (addPCIeRoot) {
3483 if (pciRoot >= 0) {
3484 if (def->controllers[pciRoot]->model != VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT) {
3485 virReportError(VIR_ERR_XML_ERROR,
3486 _("The PCI controller with index='0' must be "
3487 "model='pcie-root' for this machine type, "
3488 "but model='%s' was found instead"),
3489 virDomainControllerModelPCITypeToString(def->controllers[pciRoot]->model));
3490 goto cleanup;
3492 } else if (!virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0,
3493 VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)) {
3494 goto cleanup;
3498 if (addDefaultMemballoon && !def->memballoon) {
3499 virDomainMemballoonDefPtr memballoon;
3500 if (VIR_ALLOC(memballoon) < 0)
3501 goto cleanup;
3503 memballoon->model = VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO;
3504 def->memballoon = memballoon;
3507 if (STRPREFIX(def->os.machine, "s390-virtio") &&
3508 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_S390) && def->memballoon)
3509 def->memballoon->model = VIR_DOMAIN_MEMBALLOON_MODEL_NONE;
3511 if (addDefaultUSBMouse) {
3512 bool hasUSBTablet = false;
3513 size_t j;
3515 for (j = 0; j < def->ninputs; j++) {
3516 if (def->inputs[j]->type == VIR_DOMAIN_INPUT_TYPE_TABLET &&
3517 def->inputs[j]->bus == VIR_DOMAIN_INPUT_BUS_USB) {
3518 hasUSBTablet = true;
3519 break;
3523 /* Historically, we have automatically added USB keyboard and
3524 * mouse to some guests. While the former device is generally
3525 * safe to have, adding the latter is undesiderable if a USB
3526 * tablet is already present in the guest */
3527 if (hasUSBTablet)
3528 addDefaultUSBMouse = false;
3531 if (addDefaultUSBKBD &&
3532 def->ngraphics > 0 &&
3533 virDomainDefMaybeAddInput(def,
3534 VIR_DOMAIN_INPUT_TYPE_KBD,
3535 VIR_DOMAIN_INPUT_BUS_USB) < 0)
3536 goto cleanup;
3538 if (addDefaultUSBMouse &&
3539 def->ngraphics > 0 &&
3540 virDomainDefMaybeAddInput(def,
3541 VIR_DOMAIN_INPUT_TYPE_MOUSE,
3542 VIR_DOMAIN_INPUT_BUS_USB) < 0)
3543 goto cleanup;
3545 if (addPanicDevice) {
3546 size_t j;
3547 for (j = 0; j < def->npanics; j++) {
3548 if (def->panics[j]->model == VIR_DOMAIN_PANIC_MODEL_DEFAULT ||
3549 (ARCH_IS_PPC64(def->os.arch) &&
3550 def->panics[j]->model == VIR_DOMAIN_PANIC_MODEL_PSERIES) ||
3551 (ARCH_IS_S390(def->os.arch) &&
3552 def->panics[j]->model == VIR_DOMAIN_PANIC_MODEL_S390))
3553 break;
3556 if (j == def->npanics) {
3557 virDomainPanicDefPtr panic;
3558 if (VIR_ALLOC(panic) < 0 ||
3559 VIR_APPEND_ELEMENT_COPY(def->panics,
3560 def->npanics, panic) < 0) {
3561 VIR_FREE(panic);
3562 goto cleanup;
3567 ret = 0;
3568 cleanup:
3569 return ret;
3574 * qemuDomainDefEnableDefaultFeatures:
3575 * @def: domain definition
3576 * @qemuCaps: QEMU capabilities
3578 * Make sure that features that should be enabled by default are actually
3579 * enabled and configure default values related to those features.
3581 static void
3582 qemuDomainDefEnableDefaultFeatures(virDomainDefPtr def,
3583 virQEMUCapsPtr qemuCaps)
3585 /* The virt machine type always uses GIC: if the relevant information
3586 * was not included in the domain XML, we need to choose a suitable
3587 * GIC version ourselves */
3588 if ((def->features[VIR_DOMAIN_FEATURE_GIC] == VIR_TRISTATE_SWITCH_ABSENT &&
3589 qemuDomainIsARMVirt(def)) ||
3590 (def->features[VIR_DOMAIN_FEATURE_GIC] == VIR_TRISTATE_SWITCH_ON &&
3591 def->gic_version == VIR_GIC_VERSION_NONE)) {
3592 virGICVersion version;
3594 VIR_DEBUG("Looking for usable GIC version in domain capabilities");
3595 for (version = VIR_GIC_VERSION_LAST - 1;
3596 version > VIR_GIC_VERSION_NONE;
3597 version--) {
3599 /* We want to use the highest available GIC version for guests;
3600 * however, the emulated GICv3 is currently lacking a MSI controller,
3601 * making it unsuitable for the pure PCIe topology we aim for.
3603 * For that reason, we skip this step entirely for TCG guests,
3604 * and rely on the code below to pick the default version, GICv2,
3605 * which supports all the features we need.
3607 * See https://bugzilla.redhat.com/show_bug.cgi?id=1414081 */
3608 if (version == VIR_GIC_VERSION_3 &&
3609 def->virtType == VIR_DOMAIN_VIRT_QEMU) {
3610 continue;
3613 if (virQEMUCapsSupportsGICVersion(qemuCaps,
3614 def->virtType,
3615 version)) {
3616 VIR_DEBUG("Using GIC version %s",
3617 virGICVersionTypeToString(version));
3618 def->gic_version = version;
3619 break;
3623 /* Use the default GIC version (GICv2) as a last-ditch attempt
3624 * if no match could be found above */
3625 if (def->gic_version == VIR_GIC_VERSION_NONE) {
3626 VIR_DEBUG("Using GIC version 2 (default)");
3627 def->gic_version = VIR_GIC_VERSION_2;
3630 /* Even if we haven't found a usable GIC version in the domain
3631 * capabilities, we still want to enable this */
3632 def->features[VIR_DOMAIN_FEATURE_GIC] = VIR_TRISTATE_SWITCH_ON;
3637 static int
3638 qemuCanonicalizeMachine(virDomainDefPtr def, virQEMUCapsPtr qemuCaps)
3640 const char *canon;
3642 if (!(canon = virQEMUCapsGetCanonicalMachine(qemuCaps, def->os.machine)))
3643 return 0;
3645 if (STRNEQ(canon, def->os.machine)) {
3646 char *tmp;
3647 if (VIR_STRDUP(tmp, canon) < 0)
3648 return -1;
3649 VIR_FREE(def->os.machine);
3650 def->os.machine = tmp;
3653 return 0;
3657 static int
3658 qemuDomainRecheckInternalPaths(virDomainDefPtr def,
3659 virQEMUDriverConfigPtr cfg,
3660 unsigned int flags)
3662 size_t i = 0;
3663 size_t j = 0;
3665 for (i = 0; i < def->ngraphics; ++i) {
3666 virDomainGraphicsDefPtr graphics = def->graphics[i];
3668 for (j = 0; j < graphics->nListens; ++j) {
3669 virDomainGraphicsListenDefPtr glisten = &graphics->listens[j];
3671 /* This will happen only if we parse XML from old libvirts where
3672 * unix socket was available only for VNC graphics. In this
3673 * particular case we should follow the behavior and if we remove
3674 * the auto-generated socket based on config option from qemu.conf
3675 * we need to change the listen type to address. */
3676 if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
3677 glisten->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_SOCKET &&
3678 glisten->socket &&
3679 !glisten->autoGenerated &&
3680 STRPREFIX(glisten->socket, cfg->libDir)) {
3681 if (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) {
3682 VIR_FREE(glisten->socket);
3683 glisten->type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS;
3684 } else {
3685 glisten->fromConfig = true;
3691 return 0;
3695 static int
3696 qemuDomainDefVcpusPostParse(virDomainDefPtr def)
3698 unsigned int maxvcpus = virDomainDefGetVcpusMax(def);
3699 virDomainVcpuDefPtr vcpu;
3700 virDomainVcpuDefPtr prevvcpu;
3701 size_t i;
3702 bool has_order = false;
3704 /* vcpu 0 needs to be present, first, and non-hotpluggable */
3705 vcpu = virDomainDefGetVcpu(def, 0);
3706 if (!vcpu->online) {
3707 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3708 _("vcpu 0 can't be offline"));
3709 return -1;
3711 if (vcpu->hotpluggable == VIR_TRISTATE_BOOL_YES) {
3712 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3713 _("vcpu0 can't be hotpluggable"));
3714 return -1;
3716 if (vcpu->order != 0 && vcpu->order != 1) {
3717 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3718 _("vcpu0 must be enabled first"));
3719 return -1;
3722 if (vcpu->order != 0)
3723 has_order = true;
3725 prevvcpu = vcpu;
3727 /* all online vcpus or non online vcpu need to have order set */
3728 for (i = 1; i < maxvcpus; i++) {
3729 vcpu = virDomainDefGetVcpu(def, i);
3731 if (vcpu->online &&
3732 (vcpu->order != 0) != has_order) {
3733 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3734 _("all vcpus must have either set or unset order"));
3735 return -1;
3738 /* few conditions for non-hotpluggable (thus online) vcpus */
3739 if (vcpu->hotpluggable == VIR_TRISTATE_BOOL_NO) {
3740 /* they can be ordered only at the beginning */
3741 if (prevvcpu->hotpluggable == VIR_TRISTATE_BOOL_YES) {
3742 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3743 _("online non-hotpluggable vcpus need to be "
3744 "ordered prior to hotplugable vcpus"));
3745 return -1;
3748 /* they need to be in order (qemu doesn't support any order yet).
3749 * Also note that multiple vcpus may share order on some platforms */
3750 if (prevvcpu->order > vcpu->order) {
3751 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3752 _("online non-hotpluggable vcpus must be ordered "
3753 "in ascending order"));
3754 return -1;
3758 prevvcpu = vcpu;
3761 return 0;
3765 static int
3766 qemuDomainDefCPUPostParse(virDomainDefPtr def)
3768 if (!def->cpu)
3769 return 0;
3771 if (def->cpu->cache) {
3772 virCPUCacheDefPtr cache = def->cpu->cache;
3774 if (!ARCH_IS_X86(def->os.arch)) {
3775 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3776 _("CPU cache specification is not supported "
3777 "for '%s' architecture"),
3778 virArchToString(def->os.arch));
3779 return -1;
3782 switch (cache->mode) {
3783 case VIR_CPU_CACHE_MODE_EMULATE:
3784 if (cache->level != 3) {
3785 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3786 _("CPU cache mode '%s' can only be used with "
3787 "level='3'"),
3788 virCPUCacheModeTypeToString(cache->mode));
3789 return -1;
3791 break;
3793 case VIR_CPU_CACHE_MODE_PASSTHROUGH:
3794 if (def->cpu->mode != VIR_CPU_MODE_HOST_PASSTHROUGH) {
3795 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3796 _("CPU cache mode '%s' can only be used with "
3797 "'%s' CPUs"),
3798 virCPUCacheModeTypeToString(cache->mode),
3799 virCPUModeTypeToString(VIR_CPU_MODE_HOST_PASSTHROUGH));
3800 return -1;
3803 if (cache->level != -1) {
3804 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3805 _("unsupported CPU cache level for mode '%s'"),
3806 virCPUCacheModeTypeToString(cache->mode));
3807 return -1;
3809 break;
3811 case VIR_CPU_CACHE_MODE_DISABLE:
3812 if (cache->level != -1) {
3813 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3814 _("unsupported CPU cache level for mode '%s'"),
3815 virCPUCacheModeTypeToString(cache->mode));
3816 return -1;
3818 break;
3820 case VIR_CPU_CACHE_MODE_LAST:
3821 break;
3825 /* Nothing to be done if only CPU topology is specified. */
3826 if (def->cpu->mode == VIR_CPU_MODE_CUSTOM &&
3827 !def->cpu->model)
3828 return 0;
3830 if (def->cpu->check != VIR_CPU_CHECK_DEFAULT)
3831 return 0;
3833 switch ((virCPUMode) def->cpu->mode) {
3834 case VIR_CPU_MODE_HOST_PASSTHROUGH:
3835 def->cpu->check = VIR_CPU_CHECK_NONE;
3836 break;
3838 case VIR_CPU_MODE_HOST_MODEL:
3839 def->cpu->check = VIR_CPU_CHECK_PARTIAL;
3840 break;
3842 case VIR_CPU_MODE_CUSTOM:
3843 /* Custom CPUs in TCG mode are not compared to host CPU by default. */
3844 if (def->virtType == VIR_DOMAIN_VIRT_QEMU)
3845 def->cpu->check = VIR_CPU_CHECK_NONE;
3846 else
3847 def->cpu->check = VIR_CPU_CHECK_PARTIAL;
3848 break;
3850 case VIR_CPU_MODE_LAST:
3851 break;
3854 return 0;
3858 static int
3859 qemuDomainDefTsegPostParse(virDomainDefPtr def,
3860 virQEMUCapsPtr qemuCaps)
3862 if (def->features[VIR_DOMAIN_FEATURE_SMM] != VIR_TRISTATE_SWITCH_ON)
3863 return 0;
3865 if (!def->tseg_specified)
3866 return 0;
3868 if (!qemuDomainIsQ35(def)) {
3869 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3870 _("SMM TSEG is only supported with q35 machine type"));
3871 return -1;
3874 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MCH_EXTENDED_TSEG_MBYTES)) {
3875 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3876 _("Setting TSEG size is not supported with this QEMU binary"));
3877 return -1;
3880 if (def->tseg_size & ((1 << 20) - 1)) {
3881 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3882 _("SMM TSEG size must be divisible by 1 MiB"));
3883 return -1;
3886 return 0;
3890 static int
3891 qemuDomainDefPostParseBasic(virDomainDefPtr def,
3892 virCapsPtr caps,
3893 void *opaque ATTRIBUTE_UNUSED)
3895 /* check for emulator and create a default one if needed */
3896 if (!def->emulator &&
3897 !(def->emulator = virDomainDefGetDefaultEmulator(def, caps)))
3898 return 1;
3900 return 0;
3904 static int
3905 qemuDomainDefPostParse(virDomainDefPtr def,
3906 virCapsPtr caps ATTRIBUTE_UNUSED,
3907 unsigned int parseFlags,
3908 void *opaque,
3909 void *parseOpaque)
3911 virQEMUDriverPtr driver = opaque;
3912 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3913 /* Note that qemuCaps may be NULL when this function is called. This
3914 * function shall not fail in that case. It will be re-run on VM startup
3915 * with the capabilities populated. */
3916 virQEMUCapsPtr qemuCaps = parseOpaque;
3917 int ret = -1;
3919 if (def->os.bootloader || def->os.bootloaderArgs) {
3920 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3921 _("bootloader is not supported by QEMU"));
3922 goto cleanup;
3925 if (!def->os.machine) {
3926 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3927 _("missing machine type"));
3928 goto cleanup;
3931 if (qemuDomainNVRAMPathGenerate(cfg, def) < 0)
3932 goto cleanup;
3934 if (qemuDomainDefAddDefaultDevices(def, qemuCaps) < 0)
3935 goto cleanup;
3937 if (qemuCanonicalizeMachine(def, qemuCaps) < 0)
3938 goto cleanup;
3940 qemuDomainDefEnableDefaultFeatures(def, qemuCaps);
3942 if (qemuDomainRecheckInternalPaths(def, cfg, parseFlags) < 0)
3943 goto cleanup;
3945 if (qemuSecurityVerify(driver->securityManager, def) < 0)
3946 goto cleanup;
3948 if (qemuDomainDefVcpusPostParse(def) < 0)
3949 goto cleanup;
3951 if (qemuDomainDefCPUPostParse(def) < 0)
3952 goto cleanup;
3954 if (qemuDomainDefTsegPostParse(def, qemuCaps) < 0)
3955 goto cleanup;
3957 ret = 0;
3958 cleanup:
3959 virObjectUnref(cfg);
3960 return ret;
3965 * qemuDomainDefGetVcpuHotplugGranularity:
3966 * @def: domain definition
3968 * With QEMU 2.7 and newer, vCPUs can only be hotplugged in groups that
3969 * respect the guest's hotplug granularity; because of that, QEMU will
3970 * not allow guests to start unless the initial number of vCPUs is a
3971 * multiple of the hotplug granularity.
3973 * Returns the vCPU hotplug granularity.
3975 static unsigned int
3976 qemuDomainDefGetVcpuHotplugGranularity(const virDomainDef *def)
3978 /* If the guest CPU topology has not been configured, assume we
3979 * can hotplug vCPUs one at a time */
3980 if (!def->cpu || def->cpu->sockets == 0)
3981 return 1;
3983 /* For pSeries guests, hotplug can only be performed one core
3984 * at a time, so the vCPU hotplug granularity is the number
3985 * of threads per core */
3986 if (qemuDomainIsPSeries(def))
3987 return def->cpu->threads;
3989 /* In all other cases, we can hotplug vCPUs one at a time */
3990 return 1;
3994 #define QEMU_MAX_VCPUS_WITHOUT_EIM 255
3997 static int
3998 qemuDomainDefValidateFeatures(const virDomainDef *def,
3999 virQEMUCapsPtr qemuCaps)
4001 size_t i;
4003 for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
4004 const char *featureName = virDomainFeatureTypeToString(i);
4006 switch ((virDomainFeature) i) {
4007 case VIR_DOMAIN_FEATURE_IOAPIC:
4008 if (def->features[i] != VIR_DOMAIN_IOAPIC_NONE &&
4009 !ARCH_IS_X86(def->os.arch)) {
4010 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4011 _("The '%s' feature is not supported for "
4012 "architecture '%s' or machine type '%s'"),
4013 featureName,
4014 virArchToString(def->os.arch),
4015 def->os.machine);
4016 return -1;
4018 break;
4020 case VIR_DOMAIN_FEATURE_HPT:
4021 case VIR_DOMAIN_FEATURE_HTM:
4022 case VIR_DOMAIN_FEATURE_NESTED_HV:
4023 if (def->features[i] != VIR_TRISTATE_SWITCH_ABSENT &&
4024 !qemuDomainIsPSeries(def)) {
4025 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4026 _("The '%s' feature is not supported for "
4027 "architecture '%s' or machine type '%s'"),
4028 featureName,
4029 virArchToString(def->os.arch),
4030 def->os.machine);
4031 return -1;
4033 break;
4035 case VIR_DOMAIN_FEATURE_GIC:
4036 if (def->features[i] == VIR_TRISTATE_SWITCH_ON &&
4037 !qemuDomainIsARMVirt(def)) {
4038 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4039 _("The '%s' feature is not supported for "
4040 "architecture '%s' or machine type '%s'"),
4041 featureName,
4042 virArchToString(def->os.arch),
4043 def->os.machine);
4044 return -1;
4046 break;
4048 case VIR_DOMAIN_FEATURE_SMM:
4049 if (def->features[i] != VIR_TRISTATE_SWITCH_ABSENT &&
4050 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_SMM_OPT)) {
4051 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4052 _("smm is not available with this QEMU binary"));
4053 return -1;
4055 break;
4057 case VIR_DOMAIN_FEATURE_ACPI:
4058 case VIR_DOMAIN_FEATURE_APIC:
4059 case VIR_DOMAIN_FEATURE_PAE:
4060 case VIR_DOMAIN_FEATURE_HAP:
4061 case VIR_DOMAIN_FEATURE_VIRIDIAN:
4062 case VIR_DOMAIN_FEATURE_PRIVNET:
4063 case VIR_DOMAIN_FEATURE_HYPERV:
4064 case VIR_DOMAIN_FEATURE_KVM:
4065 case VIR_DOMAIN_FEATURE_PVSPINLOCK:
4066 case VIR_DOMAIN_FEATURE_CAPABILITIES:
4067 case VIR_DOMAIN_FEATURE_PMU:
4068 case VIR_DOMAIN_FEATURE_VMPORT:
4069 case VIR_DOMAIN_FEATURE_VMCOREINFO:
4070 case VIR_DOMAIN_FEATURE_MSRS:
4071 case VIR_DOMAIN_FEATURE_LAST:
4072 break;
4076 return 0;
4080 static int
4081 qemuDomainDefValidateMemory(const virDomainDef *def,
4082 virQEMUCapsPtr qemuCaps)
4084 const long system_page_size = virGetSystemPageSizeKB();
4085 const virDomainMemtune *mem = &def->mem;
4087 if (mem->nhugepages == 0)
4088 return 0;
4090 if (mem->allocation == VIR_DOMAIN_MEMORY_ALLOCATION_ONDEMAND) {
4091 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4092 _("hugepages are not allowed with memory "
4093 "allocation ondemand"));
4094 return -1;
4097 if (mem->source == VIR_DOMAIN_MEMORY_SOURCE_ANONYMOUS) {
4098 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4099 _("hugepages are not allowed with anonymous "
4100 "memory source"));
4101 return -1;
4104 if (mem->source == VIR_DOMAIN_MEMORY_SOURCE_MEMFD &&
4105 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_MEMFD_HUGETLB)) {
4106 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4107 _("hugepages is not supported with memfd memory source"));
4108 return -1;
4111 /* We can't guarantee any other mem.access
4112 * if no guest NUMA nodes are defined. */
4113 if (mem->hugepages[0].size != system_page_size &&
4114 virDomainNumaGetNodeCount(def->numa) == 0 &&
4115 mem->access != VIR_DOMAIN_MEMORY_ACCESS_DEFAULT &&
4116 mem->access != VIR_DOMAIN_MEMORY_ACCESS_PRIVATE) {
4117 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4118 _("memory access mode '%s' not supported "
4119 "without guest numa node"),
4120 virDomainMemoryAccessTypeToString(mem->access));
4121 return -1;
4124 return 0;
4128 static int
4129 qemuDomainValidateCpuCount(const virDomainDef *def,
4130 virQEMUCapsPtr qemuCaps)
4132 unsigned int maxCpus = virQEMUCapsGetMachineMaxCpus(qemuCaps, def->os.machine);
4134 if (virDomainDefGetVcpus(def) == 0) {
4135 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4136 _("Domain requires at least 1 vCPU"));
4137 return -1;
4140 if (maxCpus > 0 && virDomainDefGetVcpusMax(def) > maxCpus) {
4141 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4142 _("Maximum CPUs greater than specified machine "
4143 "type limit %u"), maxCpus);
4144 return -1;
4147 return 0;
4151 static int
4152 qemuDomainDefValidate(const virDomainDef *def,
4153 virCapsPtr caps ATTRIBUTE_UNUSED,
4154 void *opaque)
4156 virQEMUDriverPtr driver = opaque;
4157 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
4158 virQEMUCapsPtr qemuCaps = NULL;
4159 int ret = -1;
4160 size_t i;
4162 if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache,
4163 def->emulator)))
4164 goto cleanup;
4166 if (def->mem.min_guarantee) {
4167 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4168 _("Parameter 'min_guarantee' not supported by QEMU."));
4169 goto cleanup;
4172 /* On x86, UEFI requires ACPI */
4173 if (def->os.loader &&
4174 def->os.loader->type == VIR_DOMAIN_LOADER_TYPE_PFLASH &&
4175 ARCH_IS_X86(def->os.arch) &&
4176 def->features[VIR_DOMAIN_FEATURE_ACPI] != VIR_TRISTATE_SWITCH_ON) {
4177 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4178 _("UEFI requires ACPI on this architecture"));
4179 goto cleanup;
4182 /* On aarch64, ACPI requires UEFI */
4183 if (def->features[VIR_DOMAIN_FEATURE_ACPI] == VIR_TRISTATE_SWITCH_ON &&
4184 def->os.arch == VIR_ARCH_AARCH64 &&
4185 (!def->os.loader ||
4186 def->os.loader->type != VIR_DOMAIN_LOADER_TYPE_PFLASH)) {
4187 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4188 _("ACPI requires UEFI on this architecture"));
4189 goto cleanup;
4192 if (def->os.loader &&
4193 def->os.loader->secure == VIR_TRISTATE_BOOL_YES) {
4194 /* These are the QEMU implementation limitations. But we
4195 * have to live with them for now. */
4197 if (!qemuDomainIsQ35(def)) {
4198 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4199 _("Secure boot is supported with q35 machine types only"));
4200 goto cleanup;
4203 /* Now, technically it is possible to have secure boot on
4204 * 32bits too, but that would require some -cpu xxx magic
4205 * too. Not worth it unless we are explicitly asked. */
4206 if (def->os.arch != VIR_ARCH_X86_64) {
4207 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4208 _("Secure boot is supported for x86_64 architecture only"));
4209 goto cleanup;
4212 /* SMM will be enabled by qemuFirmwareFillDomain() if needed. */
4213 if (def->os.firmware == VIR_DOMAIN_OS_DEF_FIRMWARE_NONE &&
4214 def->features[VIR_DOMAIN_FEATURE_SMM] != VIR_TRISTATE_SWITCH_ON) {
4215 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4216 _("Secure boot requires SMM feature enabled"));
4217 goto cleanup;
4221 /* QEMU 2.7 (detected via the availability of query-hotpluggable-cpus)
4222 * enforces stricter rules than previous versions when it comes to guest
4223 * CPU topology. Verify known constraints are respected */
4224 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_QUERY_HOTPLUGGABLE_CPUS)) {
4225 unsigned int topologycpus;
4226 unsigned int granularity;
4228 /* Starting from QEMU 2.5, max vCPU count and overall vCPU topology
4229 * must agree. We only actually enforce this with QEMU 2.7+, due
4230 * to the capability check above */
4231 if (virDomainDefGetVcpusTopology(def, &topologycpus) == 0 &&
4232 topologycpus != virDomainDefGetVcpusMax(def)) {
4233 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4234 _("CPU topology doesn't match maximum vcpu count"));
4235 goto cleanup;
4238 /* vCPU hotplug granularity must be respected */
4239 granularity = qemuDomainDefGetVcpuHotplugGranularity(def);
4240 if ((virDomainDefGetVcpus(def) % granularity) != 0) {
4241 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4242 _("vCPUs count must be a multiple of the vCPU "
4243 "hotplug granularity (%u)"),
4244 granularity);
4245 goto cleanup;
4249 if (qemuDomainValidateCpuCount(def, qemuCaps) < 0)
4250 goto cleanup;
4252 if (ARCH_IS_X86(def->os.arch) &&
4253 virDomainDefGetVcpusMax(def) > QEMU_MAX_VCPUS_WITHOUT_EIM) {
4254 if (!qemuDomainIsQ35(def)) {
4255 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4256 _("more than %d vCPUs are only supported on "
4257 "q35-based machine types"),
4258 QEMU_MAX_VCPUS_WITHOUT_EIM);
4259 goto cleanup;
4261 if (!def->iommu || def->iommu->eim != VIR_TRISTATE_SWITCH_ON) {
4262 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4263 _("more than %d vCPUs require extended interrupt "
4264 "mode enabled on the iommu device"),
4265 QEMU_MAX_VCPUS_WITHOUT_EIM);
4266 goto cleanup;
4270 if (def->nresctrls &&
4271 def->virtType != VIR_DOMAIN_VIRT_KVM) {
4272 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4273 _("cachetune is only supported for KVM domains"));
4274 goto cleanup;
4277 if (qemuDomainDefValidateFeatures(def, qemuCaps) < 0)
4278 goto cleanup;
4280 if (qemuDomainDefValidateMemory(def, qemuCaps) < 0)
4281 goto cleanup;
4283 if (cfg->vncTLS && cfg->vncTLSx509secretUUID &&
4284 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_TLS_CREDS_X509)) {
4285 for (i = 0; i < def->ngraphics; i++) {
4286 if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
4287 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4288 _("encrypted VNC TLS keys are not supported with "
4289 "this QEMU binary"));
4290 goto cleanup;
4295 ret = 0;
4297 cleanup:
4298 virObjectUnref(qemuCaps);
4299 virObjectUnref(cfg);
4300 return ret;
4304 static bool
4305 qemuDomainNetSupportsCoalesce(virDomainNetType type)
4307 switch (type) {
4308 case VIR_DOMAIN_NET_TYPE_NETWORK:
4309 case VIR_DOMAIN_NET_TYPE_BRIDGE:
4310 return true;
4311 case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
4312 case VIR_DOMAIN_NET_TYPE_ETHERNET:
4313 case VIR_DOMAIN_NET_TYPE_DIRECT:
4314 case VIR_DOMAIN_NET_TYPE_HOSTDEV:
4315 case VIR_DOMAIN_NET_TYPE_USER:
4316 case VIR_DOMAIN_NET_TYPE_SERVER:
4317 case VIR_DOMAIN_NET_TYPE_CLIENT:
4318 case VIR_DOMAIN_NET_TYPE_MCAST:
4319 case VIR_DOMAIN_NET_TYPE_INTERNAL:
4320 case VIR_DOMAIN_NET_TYPE_UDP:
4321 case VIR_DOMAIN_NET_TYPE_LAST:
4322 break;
4324 return false;
4328 static int
4329 qemuDomainChrSourceReconnectDefValidate(const virDomainChrSourceReconnectDef *def)
4331 if (def->enabled == VIR_TRISTATE_BOOL_YES &&
4332 def->timeout == 0) {
4333 virReportError(VIR_ERR_INVALID_ARG, "%s",
4334 _("chardev reconnect source timeout cannot be '0'"));
4335 return -1;
4338 return 0;
4342 static int
4343 qemuDomainChrSourceDefValidate(const virDomainChrSourceDef *def)
4345 switch ((virDomainChrType)def->type) {
4346 case VIR_DOMAIN_CHR_TYPE_TCP:
4347 if (qemuDomainChrSourceReconnectDefValidate(&def->data.tcp.reconnect) < 0)
4348 return -1;
4349 break;
4351 case VIR_DOMAIN_CHR_TYPE_UNIX:
4352 if (qemuDomainChrSourceReconnectDefValidate(&def->data.nix.reconnect) < 0)
4353 return -1;
4354 break;
4356 case VIR_DOMAIN_CHR_TYPE_NULL:
4357 case VIR_DOMAIN_CHR_TYPE_VC:
4358 case VIR_DOMAIN_CHR_TYPE_PTY:
4359 case VIR_DOMAIN_CHR_TYPE_DEV:
4360 case VIR_DOMAIN_CHR_TYPE_FILE:
4361 case VIR_DOMAIN_CHR_TYPE_PIPE:
4362 case VIR_DOMAIN_CHR_TYPE_STDIO:
4363 case VIR_DOMAIN_CHR_TYPE_UDP:
4364 case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
4365 case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
4366 case VIR_DOMAIN_CHR_TYPE_NMDM:
4367 case VIR_DOMAIN_CHR_TYPE_LAST:
4368 break;
4371 return 0;
4375 static int
4376 qemuDomainChrSerialTargetTypeToAddressType(int targetType)
4378 switch ((virDomainChrSerialTargetType)targetType) {
4379 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA:
4380 return VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA;
4381 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB:
4382 return VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB;
4383 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI:
4384 return VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
4385 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO:
4386 return VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
4387 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM:
4388 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP:
4389 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST:
4390 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE:
4391 break;
4394 return VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
4398 static int
4399 qemuDomainChrSerialTargetModelToTargetType(int targetModel)
4401 switch ((virDomainChrSerialTargetModel) targetModel) {
4402 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_ISA_SERIAL:
4403 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA;
4404 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_USB_SERIAL:
4405 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB;
4406 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PCI_SERIAL:
4407 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI;
4408 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SPAPR_VTY:
4409 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO;
4410 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011:
4411 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A:
4412 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM;
4413 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPCONSOLE:
4414 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPLMCONSOLE:
4415 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP;
4416 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_NONE:
4417 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_LAST:
4418 break;
4421 return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE;
4425 static int
4426 qemuDomainChrTargetDefValidate(const virDomainChrDef *chr)
4428 int expected;
4430 switch ((virDomainChrDeviceType)chr->deviceType) {
4431 case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
4433 /* Validate target type */
4434 switch ((virDomainChrSerialTargetType)chr->targetType) {
4435 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA:
4436 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB:
4437 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI:
4438 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO:
4440 expected = qemuDomainChrSerialTargetTypeToAddressType(chr->targetType);
4442 if (chr->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
4443 chr->info.type != expected) {
4444 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4445 _("Target type '%s' requires address type '%s'"),
4446 virDomainChrSerialTargetTypeToString(chr->targetType),
4447 virDomainDeviceAddressTypeToString(expected));
4448 return -1;
4450 break;
4452 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM:
4453 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP:
4454 if (chr->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
4455 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4456 _("Target type '%s' cannot have an "
4457 "associated address"),
4458 virDomainChrSerialTargetTypeToString(chr->targetType));
4459 return -1;
4461 break;
4463 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE:
4464 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST:
4465 break;
4468 /* Validate target model */
4469 switch ((virDomainChrSerialTargetModel) chr->targetModel) {
4470 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_ISA_SERIAL:
4471 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_USB_SERIAL:
4472 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PCI_SERIAL:
4473 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SPAPR_VTY:
4474 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011:
4475 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPCONSOLE:
4476 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPLMCONSOLE:
4477 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A:
4479 expected = qemuDomainChrSerialTargetModelToTargetType(chr->targetModel);
4481 if (chr->targetType != expected) {
4482 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4483 _("Target model '%s' requires target type '%s'"),
4484 virDomainChrSerialTargetModelTypeToString(chr->targetModel),
4485 virDomainChrSerialTargetTypeToString(expected));
4486 return -1;
4488 break;
4490 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_NONE:
4491 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_LAST:
4492 break;
4494 break;
4496 case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
4497 case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
4498 case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
4499 case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
4500 /* Nothing to do */
4501 break;
4504 return 0;
4508 static int
4509 qemuDomainChrDefValidate(const virDomainChrDef *dev,
4510 const virDomainDef *def)
4512 if (qemuDomainChrSourceDefValidate(dev->source) < 0)
4513 return -1;
4515 if (qemuDomainChrTargetDefValidate(dev) < 0)
4516 return -1;
4518 if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL &&
4519 (ARCH_IS_S390(def->os.arch) || qemuDomainIsPSeries(def))) {
4520 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4521 _("parallel ports are not supported"));
4522 return -1;
4525 if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL) {
4526 bool isCompatible = true;
4528 if (dev->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM) {
4529 if (dev->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011 &&
4530 !qemuDomainIsARMVirt(def)) {
4531 isCompatible = false;
4533 if (dev->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A &&
4534 !qemuDomainIsRISCVVirt(def)) {
4535 isCompatible = false;
4539 if (!qemuDomainIsPSeries(def) &&
4540 (dev->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO ||
4541 dev->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SPAPR_VTY)) {
4542 isCompatible = false;
4545 if (!ARCH_IS_S390(def->os.arch) &&
4546 (dev->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP ||
4547 dev->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPCONSOLE ||
4548 dev->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPLMCONSOLE)) {
4549 isCompatible = false;
4552 if (!isCompatible) {
4553 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4554 _("Serial device with target type '%s' and "
4555 "target model '%s' not compatible with guest "
4556 "architecture or machine type"),
4557 virDomainChrSerialTargetTypeToString(dev->targetType),
4558 virDomainChrSerialTargetModelTypeToString(dev->targetModel));
4559 return -1;
4563 return 0;
4567 static int
4568 qemuDomainSmartcardDefValidate(const virDomainSmartcardDef *def)
4570 if (def->type == VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH &&
4571 qemuDomainChrSourceDefValidate(def->data.passthru) < 0)
4572 return -1;
4574 return 0;
4578 static int
4579 qemuDomainRNGDefValidate(const virDomainRNGDef *def,
4580 virQEMUCapsPtr qemuCaps)
4582 bool modelIsSupported = false;
4584 if (def->backend == VIR_DOMAIN_RNG_BACKEND_EGD &&
4585 qemuDomainChrSourceDefValidate(def->source.chardev) < 0)
4586 return -1;
4588 switch ((virDomainRNGModel) def->model) {
4589 case VIR_DOMAIN_RNG_MODEL_VIRTIO:
4590 modelIsSupported = virQEMUCapsGet(qemuCaps,
4591 QEMU_CAPS_DEVICE_VIRTIO_RNG);
4592 break;
4593 case VIR_DOMAIN_RNG_MODEL_VIRTIO_TRANSITIONAL:
4594 case VIR_DOMAIN_RNG_MODEL_VIRTIO_NON_TRANSITIONAL:
4595 modelIsSupported = (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_RNG) &&
4596 (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_TRANSITIONAL) ||
4597 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_DISABLE_LEGACY)));
4598 break;
4599 case VIR_DOMAIN_RNG_MODEL_LAST:
4600 break;
4603 if (!modelIsSupported) {
4604 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4605 _("this qemu doesn't support RNG device type '%s'"),
4606 virDomainRNGModelTypeToString(def->model));
4607 return -1;
4610 return 0;
4614 static int
4615 qemuDomainRedirdevDefValidate(const virDomainRedirdevDef *def)
4617 if (qemuDomainChrSourceDefValidate(def->source) < 0)
4618 return -1;
4620 return 0;
4624 static int
4625 qemuDomainWatchdogDefValidate(const virDomainWatchdogDef *dev,
4626 const virDomainDef *def)
4628 switch ((virDomainWatchdogModel) dev->model) {
4629 case VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB:
4630 if (dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
4631 dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
4632 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4633 _("%s model of watchdog can go only on PCI bus"),
4634 virDomainWatchdogModelTypeToString(dev->model));
4635 return -1;
4637 break;
4639 case VIR_DOMAIN_WATCHDOG_MODEL_IB700:
4640 if (dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
4641 dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA) {
4642 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4643 _("%s model of watchdog can go only on ISA bus"),
4644 virDomainWatchdogModelTypeToString(dev->model));
4645 return -1;
4647 break;
4649 case VIR_DOMAIN_WATCHDOG_MODEL_DIAG288:
4650 if (dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
4651 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4652 _("%s model of watchdog is virtual and cannot go on any bus."),
4653 virDomainWatchdogModelTypeToString(dev->model));
4654 return -1;
4656 if (!(ARCH_IS_S390(def->os.arch))) {
4657 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4658 _("%s model of watchdog is allowed for s390 and s390x only"),
4659 virDomainWatchdogModelTypeToString(dev->model));
4660 return -1;
4662 break;
4664 case VIR_DOMAIN_WATCHDOG_MODEL_LAST:
4665 break;
4668 return 0;
4672 static int
4673 qemuDomainDeviceDefValidateNetwork(const virDomainNetDef *net)
4675 bool hasIPv4 = false;
4676 bool hasIPv6 = false;
4677 size_t i;
4679 if (net->type == VIR_DOMAIN_NET_TYPE_USER) {
4680 if (net->guestIP.nroutes) {
4681 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4682 _("Invalid attempt to set network interface "
4683 "guest-side IP route, not supported by QEMU"));
4684 return -1;
4687 for (i = 0; i < net->guestIP.nips; i++) {
4688 const virNetDevIPAddr *ip = net->guestIP.ips[i];
4690 if (VIR_SOCKET_ADDR_VALID(&net->guestIP.ips[i]->peer)) {
4691 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4692 _("Invalid attempt to set peer IP for guest"));
4693 return -1;
4696 if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET)) {
4697 if (hasIPv4) {
4698 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4699 _("Only one IPv4 address per "
4700 "interface is allowed"));
4701 return -1;
4703 hasIPv4 = true;
4705 if (ip->prefix > 0 &&
4706 (ip->prefix < 4 || ip->prefix > 27)) {
4707 virReportError(VIR_ERR_XML_ERROR, "%s",
4708 _("invalid prefix, must be in range of 4-27"));
4709 return -1;
4713 if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET6)) {
4714 if (hasIPv6) {
4715 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4716 _("Only one IPv6 address per "
4717 "interface is allowed"));
4718 return -1;
4720 hasIPv6 = true;
4722 if (ip->prefix > 120) {
4723 virReportError(VIR_ERR_XML_ERROR, "%s",
4724 _("prefix too long"));
4725 return -1;
4729 } else if (net->guestIP.nroutes || net->guestIP.nips) {
4730 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4731 _("Invalid attempt to set network interface "
4732 "guest-side IP route and/or address info, "
4733 "not supported by QEMU"));
4734 return -1;
4737 if (virDomainNetIsVirtioModel(net)) {
4738 if (net->driver.virtio.rx_queue_size & (net->driver.virtio.rx_queue_size - 1)) {
4739 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4740 _("rx_queue_size has to be a power of two"));
4741 return -1;
4743 if (net->driver.virtio.tx_queue_size & (net->driver.virtio.tx_queue_size - 1)) {
4744 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4745 _("tx_queue_size has to be a power of two"));
4746 return -1;
4750 if (net->mtu &&
4751 !qemuDomainNetSupportsMTU(net->type)) {
4752 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4753 _("setting MTU on interface type %s is not supported yet"),
4754 virDomainNetTypeToString(net->type));
4755 return -1;
4758 if (net->coalesce && !qemuDomainNetSupportsCoalesce(net->type)) {
4759 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4760 _("coalesce settings on interface type %s are not supported"),
4761 virDomainNetTypeToString(net->type));
4762 return -1;
4765 return 0;
4769 static int
4770 qemuDomainMdevDefVFIOPCIValidate(const virDomainHostdevSubsysMediatedDev *dev,
4771 const virDomainDef *def,
4772 virQEMUCapsPtr qemuCaps)
4774 if (dev->display == VIR_TRISTATE_SWITCH_ABSENT)
4775 return 0;
4777 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VFIO_PCI_DISPLAY)) {
4778 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4779 _("display property of device vfio-pci is "
4780 "not supported by this version of QEMU"));
4781 return -1;
4784 if (dev->model != VIR_MDEV_MODEL_TYPE_VFIO_PCI) {
4785 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4786 _("<hostdev> attribute 'display' is only supported"
4787 " with model='vfio-pci'"));
4789 return -1;
4792 if (dev->display == VIR_TRISTATE_SWITCH_ON) {
4793 if (def->ngraphics == 0) {
4794 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4795 _("graphics device is needed for attribute value "
4796 "'display=on' in <hostdev>"));
4797 return -1;
4801 return 0;
4805 static int
4806 qemuDomainMdevDefVFIOAPValidate(const virDomainDef *def)
4808 size_t i;
4809 bool vfioap_found = false;
4811 /* VFIO-AP is restricted to a single mediated device only */
4812 for (i = 0; i < def->nhostdevs; i++) {
4813 virDomainHostdevDefPtr hostdev = def->hostdevs[i];
4815 if (virHostdevIsMdevDevice(hostdev) &&
4816 hostdev->source.subsys.u.mdev.model == VIR_MDEV_MODEL_TYPE_VFIO_AP) {
4817 if (vfioap_found) {
4818 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4819 _("Only one hostdev of model vfio-ap is "
4820 "supported"));
4821 return -1;
4823 vfioap_found = true;
4827 return 0;
4831 static int
4832 qemuDomainMdevDefValidate(const virDomainHostdevSubsysMediatedDev *mdevsrc,
4833 const virDomainDef *def,
4834 virQEMUCapsPtr qemuCaps)
4836 switch ((virMediatedDeviceModelType) mdevsrc->model) {
4837 case VIR_MDEV_MODEL_TYPE_VFIO_PCI:
4838 return qemuDomainMdevDefVFIOPCIValidate(mdevsrc, def, qemuCaps);
4839 case VIR_MDEV_MODEL_TYPE_VFIO_AP:
4840 return qemuDomainMdevDefVFIOAPValidate(def);
4841 case VIR_MDEV_MODEL_TYPE_VFIO_CCW:
4842 break;
4843 case VIR_MDEV_MODEL_TYPE_LAST:
4844 default:
4845 virReportEnumRangeError(virMediatedDeviceModelType,
4846 mdevsrc->model);
4847 return -1;
4850 return 0;
4854 static int
4855 qemuDomainDeviceDefValidateHostdev(const virDomainHostdevDef *hostdev,
4856 const virDomainDef *def,
4857 virQEMUCapsPtr qemuCaps)
4859 const virDomainHostdevSubsysMediatedDev *mdevsrc;
4861 /* forbid capabilities mode hostdev in this kind of hypervisor */
4862 if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES) {
4863 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4864 _("hostdev mode 'capabilities' is not "
4865 "supported in %s"),
4866 virDomainVirtTypeToString(def->virtType));
4867 return -1;
4870 if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
4871 switch ((virDomainHostdevSubsysType) hostdev->source.subsys.type) {
4872 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
4873 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
4874 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
4875 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST:
4876 break;
4877 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV:
4878 mdevsrc = &hostdev->source.subsys.u.mdev;
4879 return qemuDomainMdevDefValidate(mdevsrc, def, qemuCaps);
4880 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
4881 default:
4882 virReportEnumRangeError(virDomainHostdevSubsysType,
4883 hostdev->source.subsys.type);
4884 return -1;
4888 return 0;
4892 static int
4893 qemuDomainDeviceDefValidateVideo(const virDomainVideoDef *video)
4895 switch ((virDomainVideoType) video->type) {
4896 case VIR_DOMAIN_VIDEO_TYPE_NONE:
4897 return 0;
4898 case VIR_DOMAIN_VIDEO_TYPE_XEN:
4899 case VIR_DOMAIN_VIDEO_TYPE_VBOX:
4900 case VIR_DOMAIN_VIDEO_TYPE_PARALLELS:
4901 case VIR_DOMAIN_VIDEO_TYPE_GOP:
4902 case VIR_DOMAIN_VIDEO_TYPE_DEFAULT:
4903 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4904 _("video type '%s' is not supported with QEMU"),
4905 virDomainVideoTypeToString(video->type));
4906 return -1;
4907 case VIR_DOMAIN_VIDEO_TYPE_VGA:
4908 case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
4909 case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
4910 case VIR_DOMAIN_VIDEO_TYPE_QXL:
4911 case VIR_DOMAIN_VIDEO_TYPE_VIRTIO:
4912 case VIR_DOMAIN_VIDEO_TYPE_LAST:
4913 break;
4916 if (!video->primary &&
4917 video->type != VIR_DOMAIN_VIDEO_TYPE_QXL &&
4918 video->type != VIR_DOMAIN_VIDEO_TYPE_VIRTIO) {
4919 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4920 _("video type '%s' is only valid as primary "
4921 "video device"),
4922 virDomainVideoTypeToString(video->type));
4923 return -1;
4926 if (video->accel && video->accel->accel2d == VIR_TRISTATE_SWITCH_ON) {
4927 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4928 _("qemu does not support the accel2d setting"));
4929 return -1;
4932 if (video->type == VIR_DOMAIN_VIDEO_TYPE_QXL) {
4933 if (video->vram > (UINT_MAX / 1024)) {
4934 virReportError(VIR_ERR_OVERFLOW,
4935 _("value for 'vram' must be less than '%u'"),
4936 UINT_MAX / 1024);
4937 return -1;
4939 if (video->ram > (UINT_MAX / 1024)) {
4940 virReportError(VIR_ERR_OVERFLOW,
4941 _("value for 'ram' must be less than '%u'"),
4942 UINT_MAX / 1024);
4943 return -1;
4945 if (video->vgamem) {
4946 if (video->vgamem < 1024) {
4947 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4948 _("value for 'vgamem' must be at least 1 MiB "
4949 "(1024 KiB)"));
4950 return -1;
4953 if (video->vgamem != VIR_ROUND_UP_POWER_OF_TWO(video->vgamem)) {
4954 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4955 _("value for 'vgamem' must be power of two"));
4956 return -1;
4961 if (video->type == VIR_DOMAIN_VIDEO_TYPE_VGA ||
4962 video->type == VIR_DOMAIN_VIDEO_TYPE_VMVGA) {
4963 if (video->vram && video->vram < 1024) {
4964 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4965 "%s", _("value for 'vram' must be at least "
4966 "1 MiB (1024 KiB)"));
4967 return -1;
4971 return 0;
4976 qemuDomainValidateStorageSource(virStorageSourcePtr src,
4977 virQEMUCapsPtr qemuCaps)
4979 int actualType = virStorageSourceGetActualType(src);
4981 if (src->format == VIR_STORAGE_FILE_COW) {
4982 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4983 _("'cow' storage format is not supported"));
4984 return -1;
4987 if (src->format == VIR_STORAGE_FILE_DIR) {
4988 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4989 _("'directory' storage format is not directly supported by QEMU, "
4990 "use 'dir' disk type instead"));
4991 return -1;
4994 if (src->format == VIR_STORAGE_FILE_ISO) {
4995 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4996 _("storage format 'iso' is not directly supported by QEMU, "
4997 "use 'raw' instead"));
4998 return -1;
5001 if ((src->format == VIR_STORAGE_FILE_QCOW ||
5002 src->format == VIR_STORAGE_FILE_QCOW2) &&
5003 src->encryption &&
5004 (src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_DEFAULT ||
5005 src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_QCOW)) {
5006 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5007 _("old qcow/qcow2 encryption is not supported"));
5008 return -1;
5011 if (src->format == VIR_STORAGE_FILE_QCOW2 &&
5012 src->encryption &&
5013 src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_LUKS &&
5014 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_QCOW2_LUKS)) {
5015 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5016 _("LUKS encrypted QCOW2 images are not supported by this QEMU"));
5017 return -1;
5020 if (src->format == VIR_STORAGE_FILE_FAT &&
5021 actualType != VIR_STORAGE_TYPE_DIR) {
5022 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5023 _("storage format 'fat' is supported only with 'dir' "
5024 "storage type"));
5025 return -1;
5028 if (actualType == VIR_STORAGE_TYPE_DIR) {
5029 if (src->format > 0 &&
5030 src->format != VIR_STORAGE_FILE_FAT) {
5031 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5032 _("storage type 'dir' requires use of storage format 'fat'"));
5033 return -1;
5036 if (!src->readonly) {
5037 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5038 _("virtual FAT storage can't be accessed in read-write mode"));
5039 return -1;
5043 if (src->pr &&
5044 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_PR_MANAGER_HELPER)) {
5045 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5046 _("reservations not supported with this QEMU binary"));
5047 return -1;
5050 /* Use QEMU_CAPS_ISCSI_PASSWORD_SECRET as witness that iscsi 'initiator-name'
5051 * option is available, it was introduced at the same time. */
5052 if (src->initiator.iqn &&
5053 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_ISCSI_PASSWORD_SECRET)) {
5054 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5055 _("iSCSI initiator IQN not supported with this QEMU binary"));
5056 return -1;
5059 return 0;
5064 qemuDomainDeviceDefValidateDisk(const virDomainDiskDef *disk,
5065 virQEMUCapsPtr qemuCaps)
5067 const char *driverName = virDomainDiskGetDriver(disk);
5068 virStorageSourcePtr n;
5070 if (disk->src->shared && !disk->src->readonly &&
5071 !qemuBlockStorageSourceSupportsConcurrentAccess(disk->src)) {
5072 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5073 _("shared access for disk '%s' requires use of "
5074 "supported storage format"), disk->dst);
5075 return -1;
5078 if (disk->src->readonly && disk->copy_on_read == VIR_TRISTATE_SWITCH_ON) {
5079 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5080 _("copy_on_read is not compatible with read-only disk '%s'"),
5081 disk->dst);
5082 return -1;
5085 if (disk->geometry.cylinders > 0 &&
5086 disk->geometry.heads > 0 &&
5087 disk->geometry.sectors > 0) {
5088 if (disk->bus == VIR_DOMAIN_DISK_BUS_USB ||
5089 disk->bus == VIR_DOMAIN_DISK_BUS_SD) {
5090 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5091 _("CHS geometry can not be set for '%s' bus"),
5092 virDomainDiskBusTypeToString(disk->bus));
5093 return -1;
5096 if (disk->geometry.trans != VIR_DOMAIN_DISK_TRANS_DEFAULT &&
5097 disk->bus != VIR_DOMAIN_DISK_BUS_IDE) {
5098 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5099 _("CHS translation mode can only be set for 'ide' bus not '%s'"),
5100 virDomainDiskBusTypeToString(disk->bus));
5101 return -1;
5105 if (disk->serial && disk->bus == VIR_DOMAIN_DISK_BUS_SD) {
5106 virReportError(VIR_ERR_INTERNAL_ERROR,
5107 _("Serial property not supported for drive bus '%s'"),
5108 virDomainDiskBusTypeToString(disk->bus));
5109 return -1;
5112 if (driverName && STRNEQ(driverName, "qemu")) {
5113 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5114 _("unsupported driver name '%s' for disk '%s'"),
5115 driverName, disk->dst);
5116 return -1;
5119 for (n = disk->src; virStorageSourceIsBacking(n); n = n->backingStore) {
5120 if (qemuDomainValidateStorageSource(n, qemuCaps) < 0)
5121 return -1;
5124 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
5125 disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
5126 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5127 _("disk type 'virtio' of '%s' does not support ejectable media"),
5128 disk->dst);
5129 return -1;
5132 return 0;
5136 static int
5137 qemuDomainDeviceDefValidateControllerAttributes(const virDomainControllerDef *controller)
5139 if (!(controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI &&
5140 (controller->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI ||
5141 controller->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL ||
5142 controller->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL))) {
5143 if (controller->queues) {
5144 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5145 _("'queues' is only supported by virtio-scsi controller"));
5146 return -1;
5148 if (controller->cmd_per_lun) {
5149 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5150 _("'cmd_per_lun' is only supported by virtio-scsi controller"));
5151 return -1;
5153 if (controller->max_sectors) {
5154 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5155 _("'max_sectors' is only supported by virtio-scsi controller"));
5156 return -1;
5158 if (controller->ioeventfd) {
5159 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5160 _("'ioeventfd' is only supported by virtio-scsi controller"));
5161 return -1;
5163 if (controller->iothread) {
5164 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5165 _("'iothread' is only supported for virtio-scsi controller"));
5166 return -1;
5170 return 0;
5175 * @qemuCaps: QEMU capabilities
5176 * @model: SCSI model to check
5178 * Using the @qemuCaps, let's ensure the provided @model can be supported
5180 * Returns true if acceptable, false otherwise with error message set.
5182 static bool
5183 qemuDomainCheckSCSIControllerModel(virQEMUCapsPtr qemuCaps,
5184 int model)
5186 switch ((virDomainControllerModelSCSI) model) {
5187 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
5188 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_LSI)) {
5189 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5190 _("This QEMU doesn't support "
5191 "the LSI 53C895A SCSI controller"));
5192 return false;
5194 break;
5195 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
5196 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL:
5197 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL:
5198 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_SCSI)) {
5199 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5200 _("This QEMU doesn't support "
5201 "virtio scsi controller"));
5202 return false;
5204 break;
5205 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
5206 /*TODO: need checking work here if necessary */
5207 break;
5208 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068:
5209 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_MPTSAS1068)) {
5210 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5211 _("This QEMU doesn't support "
5212 "the LSI SAS1068 (MPT Fusion) controller"));
5213 return false;
5215 break;
5216 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
5217 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_MEGASAS)) {
5218 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5219 _("This QEMU doesn't support "
5220 "the LSI SAS1078 (MegaRAID) controller"));
5221 return false;
5223 break;
5224 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_AUTO:
5225 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC:
5226 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI:
5227 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5228 _("Unsupported controller model: %s"),
5229 virDomainControllerModelSCSITypeToString(model));
5230 return false;
5231 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_DEFAULT:
5232 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST:
5233 virReportError(VIR_ERR_INTERNAL_ERROR,
5234 _("Unexpected SCSI controller model %d"),
5235 model);
5236 return false;
5239 return true;
5243 static int
5244 qemuDomainDeviceDefValidateControllerIDE(const virDomainControllerDef *controller,
5245 const virDomainDef *def)
5247 /* first IDE controller is implicit on various machines */
5248 if (controller->idx == 0 && qemuDomainHasBuiltinIDE(def))
5249 return 0;
5251 /* Since we currently only support the integrated IDE
5252 * controller on various boards, if we ever get to here, it's
5253 * because some other machinetype had an IDE controller
5254 * specified, or one with a single IDE controller had multiple
5255 * IDE controllers specified.
5257 if (qemuDomainHasBuiltinIDE(def))
5258 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5259 _("Only a single IDE controller is supported "
5260 "for this machine type"));
5261 else
5262 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5263 _("IDE controllers are unsupported for "
5264 "this QEMU binary or machine type"));
5265 return -1;
5269 /* qemuDomainCheckSCSIControllerIOThreads:
5270 * @controller: Pointer to controller def
5271 * @def: Pointer to domain def
5273 * If this controller definition has iothreads set, let's make sure the
5274 * configuration is right before adding to the command line
5276 * Returns true if either supported or there are no iothreads for controller;
5277 * otherwise, returns false if configuration is not quite right.
5279 static bool
5280 qemuDomainCheckSCSIControllerIOThreads(const virDomainControllerDef *controller,
5281 const virDomainDef *def)
5283 if (!controller->iothread)
5284 return true;
5286 if (controller->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
5287 controller->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
5288 controller->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
5289 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5290 _("virtio-scsi IOThreads only available for virtio "
5291 "pci and virtio ccw controllers"));
5292 return false;
5295 /* Can we find the controller iothread in the iothreadid list? */
5296 if (!virDomainIOThreadIDFind(def, controller->iothread)) {
5297 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5298 _("controller iothread '%u' not defined in iothreadid"),
5299 controller->iothread);
5300 return false;
5303 return true;
5307 static int
5308 qemuDomainDeviceDefValidateControllerSCSI(const virDomainControllerDef *controller,
5309 const virDomainDef *def)
5311 switch ((virDomainControllerModelSCSI) controller->model) {
5312 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
5313 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL:
5314 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL:
5315 if (!qemuDomainCheckSCSIControllerIOThreads(controller, def))
5316 return -1;
5317 break;
5319 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_AUTO:
5320 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC:
5321 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
5322 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068:
5323 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI:
5324 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
5325 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
5326 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_DEFAULT:
5327 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST:
5328 break;
5331 return 0;
5336 * virDomainControllerPCIModelNameToQEMUCaps:
5337 * @modelName: model name
5339 * Maps model names for PCI controllers (virDomainControllerPCIModelName)
5340 * to the QEMU capabilities required to use them (virQEMUCapsFlags).
5342 * Returns: the QEMU capability itself (>0) on success; 0 if no QEMU
5343 * capability is needed; <0 on error.
5345 static int
5346 virDomainControllerPCIModelNameToQEMUCaps(int modelName)
5348 switch ((virDomainControllerPCIModelName) modelName) {
5349 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCI_BRIDGE:
5350 return QEMU_CAPS_DEVICE_PCI_BRIDGE;
5351 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_I82801B11_BRIDGE:
5352 return QEMU_CAPS_DEVICE_DMI_TO_PCI_BRIDGE;
5353 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_IOH3420:
5354 return QEMU_CAPS_DEVICE_IOH3420;
5355 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_X3130_UPSTREAM:
5356 return QEMU_CAPS_DEVICE_X3130_UPSTREAM;
5357 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_XIO3130_DOWNSTREAM:
5358 return QEMU_CAPS_DEVICE_XIO3130_DOWNSTREAM;
5359 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB:
5360 return QEMU_CAPS_DEVICE_PXB;
5361 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB_PCIE:
5362 return QEMU_CAPS_DEVICE_PXB_PCIE;
5363 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCIE_ROOT_PORT:
5364 return QEMU_CAPS_DEVICE_PCIE_ROOT_PORT;
5365 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE:
5366 return QEMU_CAPS_DEVICE_SPAPR_PCI_HOST_BRIDGE;
5367 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCIE_PCI_BRIDGE:
5368 return QEMU_CAPS_DEVICE_PCIE_PCI_BRIDGE;
5369 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE:
5370 return 0;
5371 case VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_LAST:
5372 default:
5373 return -1;
5376 return -1;
5380 #define virReportControllerMissingOption(cont, model, modelName, option) \
5381 virReportError(VIR_ERR_INTERNAL_ERROR, \
5382 _("Required option '%s' is not set for PCI controller " \
5383 "with index '%d', model '%s' and modelName '%s'"), \
5384 (option), (cont->idx), (model), (modelName));
5385 #define virReportControllerInvalidOption(cont, model, modelName, option) \
5386 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, \
5387 _("Option '%s' is not valid for PCI controller " \
5388 "with index '%d', model '%s' and modelName '%s'"), \
5389 (option), (cont->idx), (model), (modelName));
5390 #define virReportControllerInvalidValue(cont, model, modelName, option) \
5391 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, \
5392 _("Option '%s' has invalid value for PCI controller " \
5393 "with index '%d', model '%s' and modelName '%s'"), \
5394 (option), (cont->idx), (model), (modelName));
5397 static int
5398 qemuDomainDeviceDefValidateControllerPCI(const virDomainControllerDef *cont,
5399 const virDomainDef *def,
5400 virQEMUCapsPtr qemuCaps)
5403 const virDomainPCIControllerOpts *pciopts = &cont->opts.pciopts;
5404 const char *model = virDomainControllerModelPCITypeToString(cont->model);
5405 const char *modelName = virDomainControllerPCIModelNameTypeToString(pciopts->modelName);
5406 int cap = virDomainControllerPCIModelNameToQEMUCaps(pciopts->modelName);
5408 if (!model) {
5409 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5410 return -1;
5412 if (!modelName) {
5413 virReportEnumRangeError(virDomainControllerPCIModelName, pciopts->modelName);
5414 return -1;
5417 /* modelName */
5418 switch ((virDomainControllerModelPCI) cont->model) {
5419 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5420 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5421 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5422 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5423 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5424 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5425 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5426 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5427 /* modelName should have been set automatically */
5428 if (pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE) {
5429 virReportControllerMissingOption(cont, model, modelName, "modelName");
5430 return -1;
5432 break;
5434 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5435 /* modelName must be set for pSeries guests, but it's an error
5436 * for it to be set for any other guest */
5437 if (qemuDomainIsPSeries(def)) {
5438 if (pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE) {
5439 virReportControllerMissingOption(cont, model, modelName, "modelName");
5440 return -1;
5442 } else {
5443 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE) {
5444 virReportControllerInvalidOption(cont, model, modelName, "modelName");
5445 return -1;
5448 break;
5450 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5451 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE) {
5452 virReportControllerInvalidOption(cont, model, modelName, "modelName");
5453 return -1;
5455 break;
5457 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5458 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5459 default:
5460 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5461 return -1;
5464 /* modelName (cont'd) */
5465 switch ((virDomainControllerModelPCI) cont->model) {
5466 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5467 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE &&
5468 pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE) {
5469 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5470 return -1;
5472 break;
5474 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5475 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCI_BRIDGE) {
5476 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5477 return -1;
5479 break;
5481 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5482 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_I82801B11_BRIDGE) {
5483 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5484 return -1;
5486 break;
5488 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5489 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_IOH3420 &&
5490 pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCIE_ROOT_PORT) {
5491 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5492 return -1;
5494 break;
5496 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5497 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_X3130_UPSTREAM) {
5498 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5499 return -1;
5501 break;
5503 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5504 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_XIO3130_DOWNSTREAM) {
5505 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5506 return -1;
5508 break;
5510 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5511 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB) {
5512 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5513 return -1;
5515 break;
5517 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5518 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB_PCIE) {
5519 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5520 return -1;
5522 break;
5524 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5525 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE) {
5526 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5527 return -1;
5529 break;
5531 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5532 if (pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCIE_PCI_BRIDGE) {
5533 virReportControllerInvalidValue(cont, model, modelName, "modelName");
5534 return -1;
5536 break;
5538 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5539 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5540 default:
5541 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5542 return -1;
5545 /* index */
5546 switch ((virDomainControllerModelPCI) cont->model) {
5547 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5548 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5549 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5550 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5551 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5552 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5553 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5554 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5555 if (cont->idx == 0) {
5556 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5557 _("Index for '%s' controllers must be > 0"),
5558 model);
5559 return -1;
5561 break;
5563 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5564 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5565 /* pSeries guests can have multiple PHBs, so it's expected that
5566 * the index will not be zero for some of them */
5567 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT &&
5568 pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE) {
5569 break;
5572 /* For all other pci-root and pcie-root controllers, though,
5573 * the index must be zero*/
5574 if (cont->idx != 0) {
5575 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5576 _("Index for '%s' controllers must be 0"),
5577 model);
5578 return -1;
5580 break;
5582 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5583 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5584 default:
5585 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5586 return -1;
5589 /* targetIndex */
5590 switch ((virDomainControllerModelPCI) cont->model) {
5591 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5592 /* PHBs for pSeries guests must have been assigned a targetIndex */
5593 if (pciopts->targetIndex == -1 &&
5594 pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE) {
5595 virReportControllerMissingOption(cont, model, modelName, "targetIndex");
5596 return -1;
5599 /* targetIndex only applies to PHBs, so for any other pci-root
5600 * controller it being present is an error */
5601 if (pciopts->targetIndex != -1 &&
5602 pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE) {
5603 virReportControllerInvalidOption(cont, model, modelName, "targetIndex");
5604 return -1;
5606 break;
5608 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5609 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5610 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5611 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5612 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5613 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5614 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5615 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5616 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5617 if (pciopts->targetIndex != -1) {
5618 virReportControllerInvalidOption(cont, model, modelName, "targetIndex");
5619 return -1;
5621 break;
5623 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5624 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5625 default:
5626 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5627 return -1;
5630 /* pcihole64 */
5631 switch ((virDomainControllerModelPCI) cont->model) {
5632 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5633 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5634 /* The pcihole64 option only applies to x86 guests */
5635 if ((pciopts->pcihole64 ||
5636 pciopts->pcihole64size != 0) &&
5637 !ARCH_IS_X86(def->os.arch)) {
5638 virReportControllerInvalidOption(cont, model, modelName, "pcihole64");
5639 return -1;
5641 break;
5643 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5644 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5645 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5646 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5647 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5648 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5649 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5650 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5651 if (pciopts->pcihole64 ||
5652 pciopts->pcihole64size != 0) {
5653 virReportControllerInvalidOption(cont, model, modelName, "pcihole64");
5654 return -1;
5656 break;
5658 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5659 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5660 default:
5661 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5662 return -1;
5665 /* busNr */
5666 switch ((virDomainControllerModelPCI) cont->model) {
5667 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5668 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5669 if (pciopts->busNr == -1) {
5670 virReportControllerMissingOption(cont, model, modelName, "busNr");
5671 return -1;
5673 break;
5675 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5676 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5677 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5678 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5679 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5680 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5681 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5682 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5683 if (pciopts->busNr != -1) {
5684 virReportControllerInvalidOption(cont, model, modelName, "busNr");
5685 return -1;
5687 break;
5689 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5690 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5691 default:
5692 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5693 return -1;
5696 /* numaNode */
5697 switch ((virDomainControllerModelPCI) cont->model) {
5698 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5699 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5700 /* numaNode can be used for these controllers, but it's not set
5701 * automatically so it can be missing */
5702 break;
5704 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5705 /* Only PHBs support numaNode */
5706 if (pciopts->numaNode != -1 &&
5707 pciopts->modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE) {
5708 virReportControllerInvalidOption(cont, model, modelName, "numaNode");
5709 return -1;
5712 /* However, the default PHB doesn't support numaNode */
5713 if (pciopts->numaNode != -1 &&
5714 pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE &&
5715 pciopts->targetIndex == 0) {
5716 virReportControllerInvalidOption(cont, model, modelName, "numaNode");
5717 return -1;
5719 break;
5721 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5722 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5723 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5724 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5725 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5726 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5727 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5728 if (pciopts->numaNode != -1) {
5729 virReportControllerInvalidOption(cont, model, modelName, "numaNode");
5730 return -1;
5732 break;
5734 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5735 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5736 default:
5737 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5738 return -1;
5741 /* chassisNr */
5742 switch ((virDomainControllerModelPCI) cont->model) {
5743 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5744 if (pciopts->chassisNr == -1) {
5745 virReportControllerMissingOption(cont, model, modelName, "chassisNr");
5746 return -1;
5748 break;
5750 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5751 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5752 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5753 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5754 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5755 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5756 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5757 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5758 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5759 if (pciopts->chassisNr != -1) {
5760 virReportControllerInvalidOption(cont, model, modelName, "chassisNr");
5761 return -1;
5763 break;
5765 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5766 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5767 default:
5768 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5769 return -1;
5772 /* chassis and port */
5773 switch ((virDomainControllerModelPCI) cont->model) {
5774 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
5775 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
5776 if (pciopts->chassis == -1) {
5777 virReportControllerMissingOption(cont, model, modelName, "chassis");
5778 return -1;
5780 if (pciopts->port == -1) {
5781 virReportControllerMissingOption(cont, model, modelName, "port");
5782 return -1;
5784 break;
5786 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
5787 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
5788 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
5789 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
5790 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
5791 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
5792 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
5793 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
5794 if (pciopts->chassis != -1) {
5795 virReportControllerInvalidOption(cont, model, modelName, "chassis");
5796 return -1;
5798 if (pciopts->port != -1) {
5799 virReportControllerInvalidOption(cont, model, modelName, "port");
5800 return -1;
5802 break;
5804 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
5805 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
5806 default:
5807 virReportEnumRangeError(virDomainControllerModelPCI, cont->model);
5810 /* QEMU device availability */
5811 if (cap < 0) {
5812 virReportError(VIR_ERR_INTERNAL_ERROR,
5813 _("Unknown QEMU device for '%s' controller"),
5814 modelName);
5815 return -1;
5817 if (cap > 0 && !virQEMUCapsGet(qemuCaps, cap)) {
5818 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5819 _("The '%s' device is not supported by this QEMU binary"),
5820 modelName);
5821 return -1;
5824 /* PHBs didn't support numaNode from the very beginning, so an extra
5825 * capability check is required */
5826 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT &&
5827 pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE &&
5828 pciopts->numaNode != -1 &&
5829 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPAPR_PCI_HOST_BRIDGE_NUMA_NODE)) {
5830 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5831 _("Option '%s' is not supported by '%s' device with this QEMU binary"),
5832 "numaNode", modelName);
5833 return -1;
5836 return 0;
5840 #undef virReportControllerInvalidValue
5841 #undef virReportControllerInvalidOption
5842 #undef virReportControllerMissingOption
5845 static int
5846 qemuDomainDeviceDefValidateControllerSATA(const virDomainControllerDef *controller,
5847 const virDomainDef *def,
5848 virQEMUCapsPtr qemuCaps)
5850 /* first SATA controller on Q35 machines is implicit */
5851 if (controller->idx == 0 && qemuDomainIsQ35(def))
5852 return 0;
5854 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_ICH9_AHCI)) {
5855 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5856 _("SATA is not supported with this QEMU binary"));
5857 return -1;
5859 return 0;
5863 static int
5864 qemuDomainDeviceDefValidateController(const virDomainControllerDef *controller,
5865 const virDomainDef *def,
5866 virQEMUCapsPtr qemuCaps)
5868 int ret = 0;
5870 if (!qemuDomainCheckCCWS390AddressSupport(def, &controller->info, qemuCaps,
5871 "controller"))
5872 return -1;
5874 if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI &&
5875 !qemuDomainCheckSCSIControllerModel(qemuCaps, controller->model))
5876 return -1;
5878 if (qemuDomainDeviceDefValidateControllerAttributes(controller) < 0)
5879 return -1;
5881 switch ((virDomainControllerType)controller->type) {
5882 case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
5883 ret = qemuDomainDeviceDefValidateControllerIDE(controller, def);
5884 break;
5886 case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5887 ret = qemuDomainDeviceDefValidateControllerSCSI(controller, def);
5888 break;
5890 case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
5891 ret = qemuDomainDeviceDefValidateControllerPCI(controller, def,
5892 qemuCaps);
5893 break;
5895 case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
5896 ret = qemuDomainDeviceDefValidateControllerSATA(controller, def,
5897 qemuCaps);
5898 break;
5900 case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
5901 case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
5902 case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
5903 case VIR_DOMAIN_CONTROLLER_TYPE_USB:
5904 case VIR_DOMAIN_CONTROLLER_TYPE_XENBUS:
5905 case VIR_DOMAIN_CONTROLLER_TYPE_LAST:
5906 break;
5909 return ret;
5913 static int
5914 qemuDomainDeviceDefValidateVsock(const virDomainVsockDef *vsock,
5915 const virDomainDef *def,
5916 virQEMUCapsPtr qemuCaps)
5918 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VHOST_VSOCK)) {
5919 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5920 _("vsock device is not supported "
5921 "with this QEMU binary"));
5922 return -1;
5925 if (!qemuDomainCheckCCWS390AddressSupport(def, &vsock->info, qemuCaps,
5926 "vsock"))
5927 return -1;
5929 return 0;
5933 static int
5934 qemuDomainDeviceDefValidateTPM(virDomainTPMDef *tpm,
5935 const virDomainDef *def ATTRIBUTE_UNUSED)
5937 /* TPM 1.2 and 2 are not compatible, so we choose a specific version here */
5938 if (tpm->version == VIR_DOMAIN_TPM_VERSION_DEFAULT)
5939 tpm->version = VIR_DOMAIN_TPM_VERSION_1_2;
5941 switch (tpm->version) {
5942 case VIR_DOMAIN_TPM_VERSION_1_2:
5943 /* only TIS available for emulator */
5944 if (tpm->type == VIR_DOMAIN_TPM_TYPE_EMULATOR &&
5945 tpm->model != VIR_DOMAIN_TPM_MODEL_TIS) {
5946 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5947 _("Unsupported interface %s for TPM 1.2"),
5948 virDomainTPMModelTypeToString(tpm->model));
5949 return -1;
5951 break;
5952 case VIR_DOMAIN_TPM_VERSION_2_0:
5953 case VIR_DOMAIN_TPM_VERSION_DEFAULT:
5954 case VIR_DOMAIN_TPM_VERSION_LAST:
5955 break;
5957 return 0;
5961 static int
5962 qemuDomainDeviceDefValidateGraphics(const virDomainGraphicsDef *graphics,
5963 const virDomainDef *def,
5964 virQEMUCapsPtr qemuCaps)
5966 bool have_egl_headless = false;
5967 size_t i;
5969 for (i = 0; i < def->ngraphics; i++) {
5970 if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_EGL_HEADLESS) {
5971 have_egl_headless = true;
5972 break;
5976 /* Only VNC and SPICE can be paired with egl-headless, the other types
5977 * either don't make sense to pair with egl-headless or aren't even
5978 * supported by QEMU.
5980 if (have_egl_headless) {
5981 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_EGL_HEADLESS)) {
5982 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5983 _("egl-headless display is not supported with this "
5984 "QEMU binary"));
5985 return -1;
5988 if (graphics->type != VIR_DOMAIN_GRAPHICS_TYPE_EGL_HEADLESS &&
5989 graphics->type != VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
5990 graphics->type != VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
5991 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5992 _("graphics type 'egl-headless' is only supported "
5993 "with one of: 'vnc', 'spice' graphics types"));
5994 return -1;
5997 /* '-spice gl=on' and '-display egl-headless' are mutually
5998 * exclusive
6000 if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE &&
6001 graphics->data.spice.gl == VIR_TRISTATE_BOOL_YES) {
6002 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6003 _("multiple OpenGL displays are not supported "
6004 "by QEMU"));
6005 return -1;
6009 return 0;
6013 static int
6014 qemuDomainDeviceDefValidateInput(const virDomainInputDef *input,
6015 const virDomainDef *def ATTRIBUTE_UNUSED,
6016 virQEMUCapsPtr qemuCaps)
6018 const char *baseName;
6019 int cap;
6020 int ccwCap;
6022 if (input->bus != VIR_DOMAIN_INPUT_BUS_VIRTIO)
6023 return 0;
6025 /* Only type=passthrough supports model=virtio-(non-)transitional */
6026 switch ((virDomainInputModel)input->model) {
6027 case VIR_DOMAIN_INPUT_MODEL_VIRTIO_TRANSITIONAL:
6028 case VIR_DOMAIN_INPUT_MODEL_VIRTIO_NON_TRANSITIONAL:
6029 switch ((virDomainInputType)input->type) {
6030 case VIR_DOMAIN_INPUT_TYPE_MOUSE:
6031 case VIR_DOMAIN_INPUT_TYPE_TABLET:
6032 case VIR_DOMAIN_INPUT_TYPE_KBD:
6033 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6034 _("virtio (non-)transitional models are not "
6035 "supported for input type=%s"),
6036 virDomainInputTypeToString(input->type));
6037 return -1;
6038 case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
6039 break;
6040 case VIR_DOMAIN_INPUT_TYPE_LAST:
6041 default:
6042 virReportEnumRangeError(virDomainInputType,
6043 input->type);
6044 return -1;
6046 break;
6047 case VIR_DOMAIN_INPUT_MODEL_VIRTIO:
6048 case VIR_DOMAIN_INPUT_MODEL_DEFAULT:
6049 break;
6050 case VIR_DOMAIN_INPUT_MODEL_LAST:
6051 default:
6052 virReportEnumRangeError(virDomainInputModel,
6053 input->model);
6054 return -1;
6057 switch ((virDomainInputType)input->type) {
6058 case VIR_DOMAIN_INPUT_TYPE_MOUSE:
6059 baseName = "virtio-mouse";
6060 cap = QEMU_CAPS_VIRTIO_MOUSE;
6061 ccwCap = QEMU_CAPS_DEVICE_VIRTIO_MOUSE_CCW;
6062 break;
6063 case VIR_DOMAIN_INPUT_TYPE_TABLET:
6064 baseName = "virtio-tablet";
6065 cap = QEMU_CAPS_VIRTIO_TABLET;
6066 ccwCap = QEMU_CAPS_DEVICE_VIRTIO_TABLET_CCW;
6067 break;
6068 case VIR_DOMAIN_INPUT_TYPE_KBD:
6069 baseName = "virtio-keyboard";
6070 cap = QEMU_CAPS_VIRTIO_KEYBOARD;
6071 ccwCap = QEMU_CAPS_DEVICE_VIRTIO_KEYBOARD_CCW;
6072 break;
6073 case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
6074 baseName = "virtio-input-host";
6075 cap = QEMU_CAPS_VIRTIO_INPUT_HOST;
6076 ccwCap = QEMU_CAPS_LAST;
6077 break;
6078 case VIR_DOMAIN_INPUT_TYPE_LAST:
6079 default:
6080 virReportEnumRangeError(virDomainInputType,
6081 input->type);
6082 return -1;
6085 if (!virQEMUCapsGet(qemuCaps, cap) ||
6086 (input->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
6087 !virQEMUCapsGet(qemuCaps, ccwCap))) {
6088 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6089 _("%s is not supported by this QEMU binary"),
6090 baseName);
6091 return -1;
6094 return 0;
6098 static int
6099 qemuDomainDeviceDefValidateMemballoon(const virDomainMemballoonDef *memballoon,
6100 virQEMUCapsPtr qemuCaps)
6102 if (!memballoon ||
6103 memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE) {
6104 return 0;
6107 if (memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO &&
6108 memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO_TRANSITIONAL &&
6109 memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO_NON_TRANSITIONAL) {
6110 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6111 _("Memory balloon device type '%s' is not supported by this version of qemu"),
6112 virDomainMemballoonModelTypeToString(memballoon->model));
6113 return -1;
6116 if (memballoon->autodeflate != VIR_TRISTATE_SWITCH_ABSENT &&
6117 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BALLOON_AUTODEFLATE)) {
6118 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6119 _("deflate-on-oom is not supported by this QEMU binary"));
6120 return -1;
6123 return 0;
6127 static int
6128 qemuDomainDeviceDefValidateZPCIAddress(virDomainDeviceInfoPtr info,
6129 virQEMUCapsPtr qemuCaps)
6131 if (!virZPCIDeviceAddressIsEmpty(&info->addr.pci.zpci) &&
6132 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_ZPCI)) {
6133 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6134 "%s",
6135 _("This QEMU binary doesn't support zPCI"));
6136 return -1;
6139 return 0;
6143 static int
6144 qemuDomainDeviceDefValidateAddress(const virDomainDeviceDef *dev,
6145 virQEMUCapsPtr qemuCaps)
6147 virDomainDeviceInfoPtr info;
6149 if (!(info = virDomainDeviceGetInfo((virDomainDeviceDef *)dev)))
6150 return 0;
6152 if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
6153 return qemuDomainDeviceDefValidateZPCIAddress(info, qemuCaps);
6155 return 0;
6159 static int
6160 qemuDomainDeviceDefValidate(const virDomainDeviceDef *dev,
6161 const virDomainDef *def,
6162 void *opaque)
6164 int ret = 0;
6165 virQEMUDriverPtr driver = opaque;
6166 virQEMUCapsPtr qemuCaps = NULL;
6168 if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache,
6169 def->emulator)))
6170 return -1;
6172 if ((ret = qemuDomainDeviceDefValidateAddress(dev, qemuCaps)) < 0)
6173 goto cleanup;
6175 switch ((virDomainDeviceType)dev->type) {
6176 case VIR_DOMAIN_DEVICE_NET:
6177 ret = qemuDomainDeviceDefValidateNetwork(dev->data.net);
6178 break;
6180 case VIR_DOMAIN_DEVICE_CHR:
6181 ret = qemuDomainChrDefValidate(dev->data.chr, def);
6182 break;
6184 case VIR_DOMAIN_DEVICE_SMARTCARD:
6185 ret = qemuDomainSmartcardDefValidate(dev->data.smartcard);
6186 break;
6188 case VIR_DOMAIN_DEVICE_RNG:
6189 ret = qemuDomainRNGDefValidate(dev->data.rng, qemuCaps);
6190 break;
6192 case VIR_DOMAIN_DEVICE_REDIRDEV:
6193 ret = qemuDomainRedirdevDefValidate(dev->data.redirdev);
6194 break;
6196 case VIR_DOMAIN_DEVICE_WATCHDOG:
6197 ret = qemuDomainWatchdogDefValidate(dev->data.watchdog, def);
6198 break;
6200 case VIR_DOMAIN_DEVICE_HOSTDEV:
6201 ret = qemuDomainDeviceDefValidateHostdev(dev->data.hostdev, def,
6202 qemuCaps);
6203 break;
6205 case VIR_DOMAIN_DEVICE_VIDEO:
6206 ret = qemuDomainDeviceDefValidateVideo(dev->data.video);
6207 break;
6209 case VIR_DOMAIN_DEVICE_DISK:
6210 ret = qemuDomainDeviceDefValidateDisk(dev->data.disk, qemuCaps);
6211 break;
6213 case VIR_DOMAIN_DEVICE_CONTROLLER:
6214 ret = qemuDomainDeviceDefValidateController(dev->data.controller, def,
6215 qemuCaps);
6216 break;
6218 case VIR_DOMAIN_DEVICE_VSOCK:
6219 ret = qemuDomainDeviceDefValidateVsock(dev->data.vsock, def, qemuCaps);
6220 break;
6222 case VIR_DOMAIN_DEVICE_TPM:
6223 ret = qemuDomainDeviceDefValidateTPM(dev->data.tpm, def);
6224 break;
6226 case VIR_DOMAIN_DEVICE_GRAPHICS:
6227 ret = qemuDomainDeviceDefValidateGraphics(dev->data.graphics, def,
6228 qemuCaps);
6229 break;
6231 case VIR_DOMAIN_DEVICE_INPUT:
6232 ret = qemuDomainDeviceDefValidateInput(dev->data.input, def, qemuCaps);
6233 break;
6235 case VIR_DOMAIN_DEVICE_MEMBALLOON:
6236 ret = qemuDomainDeviceDefValidateMemballoon(dev->data.memballoon, qemuCaps);
6237 break;
6239 case VIR_DOMAIN_DEVICE_LEASE:
6240 case VIR_DOMAIN_DEVICE_FS:
6241 case VIR_DOMAIN_DEVICE_SOUND:
6242 case VIR_DOMAIN_DEVICE_HUB:
6243 case VIR_DOMAIN_DEVICE_NVRAM:
6244 case VIR_DOMAIN_DEVICE_SHMEM:
6245 case VIR_DOMAIN_DEVICE_MEMORY:
6246 case VIR_DOMAIN_DEVICE_PANIC:
6247 case VIR_DOMAIN_DEVICE_IOMMU:
6248 case VIR_DOMAIN_DEVICE_NONE:
6249 case VIR_DOMAIN_DEVICE_LAST:
6250 break;
6253 cleanup:
6254 virObjectUnref(qemuCaps);
6255 return ret;
6260 * qemuDomainDefaultNetModel:
6261 * @def: domain definition
6262 * @qemuCaps: qemu capabilities
6264 * Returns the default network model for a given domain. Note that if @qemuCaps
6265 * is NULL this function may return NULL if the default model depends on the
6266 * capabilities.
6268 static const char *
6269 qemuDomainDefaultNetModel(const virDomainDef *def,
6270 virQEMUCapsPtr qemuCaps)
6272 if (ARCH_IS_S390(def->os.arch))
6273 return "virtio";
6275 if (def->os.arch == VIR_ARCH_ARMV6L ||
6276 def->os.arch == VIR_ARCH_ARMV7L ||
6277 def->os.arch == VIR_ARCH_AARCH64) {
6278 if (STREQ(def->os.machine, "versatilepb"))
6279 return "smc91c111";
6281 if (qemuDomainIsARMVirt(def))
6282 return "virtio";
6284 /* Incomplete. vexpress (and a few others) use this, but not all
6285 * arm boards */
6286 return "lan9118";
6289 /* virtio is a sensible default for RISC-V virt guests */
6290 if (qemuDomainIsRISCVVirt(def))
6291 return "virtio";
6293 /* In all other cases the model depends on the capabilities. If they were
6294 * not provided don't report any default. */
6295 if (!qemuCaps)
6296 return NULL;
6298 /* Try several network devices in turn; each of these devices is
6299 * less likely be supported out-of-the-box by the guest operating
6300 * system than the previous one */
6301 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_RTL8139))
6302 return "rtl8139";
6303 else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_E1000))
6304 return "e1000";
6305 else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_NET))
6306 return "virtio";
6308 /* We've had no luck detecting support for any network device,
6309 * but we have to return something: might as well be rtl8139 */
6310 return "rtl8139";
6315 * Clear auto generated unix socket paths:
6317 * libvirt 1.2.18 and older:
6318 * {cfg->channelTargetDir}/{dom-name}.{target-name}
6320 * libvirt 1.2.19 - 1.3.2:
6321 * {cfg->channelTargetDir}/domain-{dom-name}/{target-name}
6323 * libvirt 1.3.3 and newer:
6324 * {cfg->channelTargetDir}/domain-{dom-id}-{short-dom-name}/{target-name}
6326 * The unix socket path was stored in config XML until libvirt 1.3.0.
6327 * If someone specifies the same path as we generate, they shouldn't do it.
6329 * This function clears the path for migration as well, so we need to clear
6330 * the path even if we are not storing it in the XML.
6332 static int
6333 qemuDomainChrDefDropDefaultPath(virDomainChrDefPtr chr,
6334 virQEMUDriverPtr driver)
6336 virQEMUDriverConfigPtr cfg;
6337 virBuffer buf = VIR_BUFFER_INITIALIZER;
6338 char *regexp = NULL;
6339 int ret = -1;
6341 if (chr->deviceType != VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL ||
6342 chr->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO ||
6343 chr->source->type != VIR_DOMAIN_CHR_TYPE_UNIX ||
6344 !chr->source->data.nix.path) {
6345 return 0;
6348 cfg = virQEMUDriverGetConfig(driver);
6350 virBufferEscapeRegex(&buf, "^%s", cfg->channelTargetDir);
6351 virBufferAddLit(&buf, "/([^/]+\\.)|(domain-[^/]+/)");
6352 virBufferEscapeRegex(&buf, "%s$", chr->target.name);
6354 if (virBufferCheckError(&buf) < 0)
6355 goto cleanup;
6357 regexp = virBufferContentAndReset(&buf);
6359 if (virStringMatch(chr->source->data.nix.path, regexp))
6360 VIR_FREE(chr->source->data.nix.path);
6362 ret = 0;
6363 cleanup:
6364 VIR_FREE(regexp);
6365 virObjectUnref(cfg);
6366 return ret;
6370 static int
6371 qemuDomainShmemDefPostParse(virDomainShmemDefPtr shm)
6373 /* This was the default since the introduction of this device. */
6374 if (shm->model != VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_DOORBELL && !shm->size)
6375 shm->size = 4 << 20;
6377 /* Nothing more to check/change for IVSHMEM */
6378 if (shm->model == VIR_DOMAIN_SHMEM_MODEL_IVSHMEM)
6379 return 0;
6381 if (!shm->server.enabled) {
6382 if (shm->model == VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_DOORBELL) {
6383 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6384 _("shmem model '%s' is supported "
6385 "only with server option enabled"),
6386 virDomainShmemModelTypeToString(shm->model));
6387 return -1;
6390 if (shm->msi.enabled) {
6391 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6392 _("shmem model '%s' doesn't support "
6393 "msi"),
6394 virDomainShmemModelTypeToString(shm->model));
6396 } else {
6397 if (shm->model == VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_PLAIN) {
6398 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6399 _("shmem model '%s' is supported "
6400 "only with server option disabled"),
6401 virDomainShmemModelTypeToString(shm->model));
6402 return -1;
6405 if (shm->size) {
6406 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6407 _("shmem model '%s' does not support size setting"),
6408 virDomainShmemModelTypeToString(shm->model));
6409 return -1;
6411 shm->msi.enabled = true;
6412 if (!shm->msi.ioeventfd)
6413 shm->msi.ioeventfd = VIR_TRISTATE_SWITCH_ON;
6416 return 0;
6420 #define QEMU_USB_XHCI_MAXPORTS 15
6423 static int
6424 qemuDomainControllerDefPostParse(virDomainControllerDefPtr cont,
6425 const virDomainDef *def,
6426 virQEMUCapsPtr qemuCaps,
6427 unsigned int parseFlags)
6429 switch ((virDomainControllerType)cont->type) {
6430 case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
6431 /* Set the default SCSI controller model if not already set */
6432 if (qemuDomainSetSCSIControllerModel(def, cont, qemuCaps) < 0)
6433 return -1;
6434 break;
6436 case VIR_DOMAIN_CONTROLLER_TYPE_USB:
6437 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT && qemuCaps) {
6438 /* Pick a suitable default model for the USB controller if none
6439 * has been selected by the user and we have the qemuCaps for
6440 * figuring out which contollers are supported.
6442 * We rely on device availability instead of setting the model
6443 * unconditionally because, for some machine types, there's a
6444 * chance we will get away with using the legacy USB controller
6445 * when the relevant device is not available.
6447 * See qemuBuildControllerDevCommandLine() */
6449 /* Default USB controller is piix3-uhci if available. */
6450 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_PIIX3_USB_UHCI))
6451 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI;
6453 if (ARCH_IS_S390(def->os.arch)) {
6454 if (cont->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
6455 /* set the default USB model to none for s390 unless an
6456 * address is found */
6457 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE;
6459 } else if (ARCH_IS_PPC64(def->os.arch)) {
6460 /* To not break migration we need to set default USB controller
6461 * for ppc64 to pci-ohci if we cannot change ABI of the VM.
6462 * The nec-usb-xhci or qemu-xhci controller is used as default
6463 * only for newly defined domains or devices. */
6464 if ((parseFlags & VIR_DOMAIN_DEF_PARSE_ABI_UPDATE) &&
6465 virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_QEMU_XHCI)) {
6466 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI;
6467 } else if ((parseFlags & VIR_DOMAIN_DEF_PARSE_ABI_UPDATE) &&
6468 virQEMUCapsGet(qemuCaps, QEMU_CAPS_NEC_USB_XHCI)) {
6469 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI;
6470 } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCI_OHCI)) {
6471 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI;
6472 } else {
6473 /* Explicitly fallback to legacy USB controller for PPC64. */
6474 cont->model = -1;
6476 } else if (def->os.arch == VIR_ARCH_AARCH64) {
6477 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_QEMU_XHCI))
6478 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI;
6479 else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NEC_USB_XHCI))
6480 cont->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI;
6483 /* forbid usb model 'qusb1' and 'qusb2' in this kind of hyperviosr */
6484 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_QUSB1 ||
6485 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_QUSB2) {
6486 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6487 _("USB controller model type 'qusb1' or 'qusb2' "
6488 "is not supported in %s"),
6489 virDomainVirtTypeToString(def->virtType));
6490 return -1;
6492 if ((cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI ||
6493 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI) &&
6494 cont->opts.usbopts.ports > QEMU_USB_XHCI_MAXPORTS) {
6495 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6496 _("'%s' controller only supports up to '%u' ports"),
6497 virDomainControllerModelUSBTypeToString(cont->model),
6498 QEMU_USB_XHCI_MAXPORTS);
6499 return -1;
6501 break;
6503 case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
6505 /* pSeries guests can have multiple pci-root controllers,
6506 * but other machine types only support a single one */
6507 if (!qemuDomainIsPSeries(def) &&
6508 (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT ||
6509 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT) &&
6510 cont->idx != 0) {
6511 virReportError(VIR_ERR_XML_ERROR, "%s",
6512 _("pci-root and pcie-root controllers "
6513 "should have index 0"));
6514 return -1;
6517 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS &&
6518 !qemuDomainIsI440FX(def)) {
6519 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6520 _("pci-expander-bus controllers are only supported "
6521 "on 440fx-based machinetypes"));
6522 return -1;
6524 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS &&
6525 !qemuDomainIsQ35(def)) {
6526 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6527 _("pcie-expander-bus controllers are only supported "
6528 "on q35-based machinetypes"));
6529 return -1;
6532 /* if a PCI expander bus or pci-root on Pseries has a NUMA node
6533 * set, make sure that NUMA node is configured in the guest
6534 * <cpu><numa> array. NUMA cell id's in this array are numbered
6535 * from 0 .. size-1.
6537 if (cont->opts.pciopts.numaNode >= 0 &&
6538 cont->opts.pciopts.numaNode >=
6539 (int)virDomainNumaGetNodeCount(def->numa)) {
6540 virReportError(VIR_ERR_XML_ERROR,
6541 _("%s with index %d is "
6542 "configured for a NUMA node (%d) "
6543 "not present in the domain's "
6544 "<cpu><numa> array (%zu)"),
6545 virDomainControllerModelPCITypeToString(cont->model),
6546 cont->idx, cont->opts.pciopts.numaNode,
6547 virDomainNumaGetNodeCount(def->numa));
6548 return -1;
6550 break;
6552 case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
6553 case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
6554 case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
6555 case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
6556 case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
6557 case VIR_DOMAIN_CONTROLLER_TYPE_XENBUS:
6558 case VIR_DOMAIN_CONTROLLER_TYPE_LAST:
6559 break;
6562 return 0;
6565 static int
6566 qemuDomainChrDefPostParse(virDomainChrDefPtr chr,
6567 const virDomainDef *def,
6568 virQEMUDriverPtr driver,
6569 unsigned int parseFlags)
6571 /* Historically, isa-serial and the default matched, so in order to
6572 * maintain backwards compatibility we map them here. The actual default
6573 * will be picked below based on the architecture and machine type. */
6574 if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
6575 chr->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA) {
6576 chr->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE;
6579 /* Set the default serial type */
6580 if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
6581 chr->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE) {
6582 if (ARCH_IS_X86(def->os.arch)) {
6583 chr->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA;
6584 } else if (qemuDomainIsPSeries(def)) {
6585 chr->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO;
6586 } else if (qemuDomainIsARMVirt(def) || qemuDomainIsRISCVVirt(def)) {
6587 chr->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM;
6588 } else if (ARCH_IS_S390(def->os.arch)) {
6589 chr->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP;
6593 /* Set the default target model */
6594 if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
6595 chr->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_NONE) {
6596 switch ((virDomainChrSerialTargetType)chr->targetType) {
6597 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA:
6598 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_ISA_SERIAL;
6599 break;
6600 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB:
6601 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_USB_SERIAL;
6602 break;
6603 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI:
6604 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PCI_SERIAL;
6605 break;
6606 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO:
6607 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SPAPR_VTY;
6608 break;
6609 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM:
6610 if (qemuDomainIsARMVirt(def)) {
6611 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011;
6612 } else if (qemuDomainIsRISCVVirt(def)) {
6613 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A;
6615 break;
6616 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP:
6617 chr->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPCONSOLE;
6618 break;
6619 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE:
6620 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST:
6621 /* Nothing to do */
6622 break;
6626 /* clear auto generated unix socket path for inactive definitions */
6627 if (parseFlags & VIR_DOMAIN_DEF_PARSE_INACTIVE) {
6628 if (qemuDomainChrDefDropDefaultPath(chr, driver) < 0)
6629 return -1;
6631 /* For UNIX chardev if no path is provided we generate one.
6632 * This also implies that the mode is 'bind'. */
6633 if (chr->source &&
6634 chr->source->type == VIR_DOMAIN_CHR_TYPE_UNIX &&
6635 !chr->source->data.nix.path) {
6636 chr->source->data.nix.listen = true;
6640 return 0;
6645 * qemuDomainDeviceDiskDefPostParseRestoreSecAlias:
6647 * Re-generate aliases for objects related to the storage source if they
6648 * were not stored in the status XML by an older libvirt.
6650 * Note that qemuCaps should be always present for a status XML.
6652 static int
6653 qemuDomainDeviceDiskDefPostParseRestoreSecAlias(virDomainDiskDefPtr disk,
6654 virQEMUCapsPtr qemuCaps,
6655 unsigned int parseFlags)
6657 qemuDomainStorageSourcePrivatePtr priv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(disk->src);
6658 bool restoreAuthSecret = false;
6659 bool restoreEncSecret = false;
6660 char *authalias = NULL;
6661 char *encalias = NULL;
6662 int ret = -1;
6664 if (!(parseFlags & VIR_DOMAIN_DEF_PARSE_STATUS) ||
6665 !qemuCaps ||
6666 virStorageSourceIsEmpty(disk->src) ||
6667 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_SECRET))
6668 return 0;
6670 /* network storage authentication secret */
6671 if (disk->src->auth &&
6672 (!priv || !priv->secinfo)) {
6674 /* only RBD and iSCSI (with capability) were supporting authentication
6675 * using secret object at the time we did not format the alias into the
6676 * status XML */
6677 if (virStorageSourceGetActualType(disk->src) == VIR_STORAGE_TYPE_NETWORK &&
6678 (disk->src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD ||
6679 (disk->src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI &&
6680 virQEMUCapsGet(qemuCaps, QEMU_CAPS_ISCSI_PASSWORD_SECRET))))
6681 restoreAuthSecret = true;
6684 /* disk encryption secret */
6685 if (disk->src->encryption &&
6686 disk->src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_LUKS &&
6687 (!priv || !priv->encinfo))
6688 restoreEncSecret = true;
6690 if (!restoreAuthSecret && !restoreEncSecret)
6691 return 0;
6693 if (!priv) {
6694 if (!(disk->src->privateData = qemuDomainStorageSourcePrivateNew()))
6695 return -1;
6697 priv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(disk->src);
6700 if (restoreAuthSecret) {
6701 if (!(authalias = qemuDomainGetSecretAESAlias(disk->info.alias, false)))
6702 goto cleanup;
6704 if (qemuStorageSourcePrivateDataAssignSecinfo(&priv->secinfo, &authalias) < 0)
6705 goto cleanup;
6708 if (restoreEncSecret) {
6709 if (!(encalias = qemuDomainGetSecretAESAlias(disk->info.alias, true)))
6710 goto cleanup;
6712 if (qemuStorageSourcePrivateDataAssignSecinfo(&priv->encinfo, &encalias) < 0)
6713 goto cleanup;
6716 ret = 0;
6718 cleanup:
6719 VIR_FREE(authalias);
6720 VIR_FREE(encalias);
6721 return ret;
6725 static int
6726 qemuDomainDeviceDiskDefPostParse(virDomainDiskDefPtr disk,
6727 virQEMUCapsPtr qemuCaps,
6728 unsigned int parseFlags)
6730 /* set default disk types and drivers */
6731 if (!virDomainDiskGetDriver(disk) &&
6732 virDomainDiskSetDriver(disk, "qemu") < 0)
6733 return -1;
6735 /* default disk format for drives */
6736 if (virDomainDiskGetFormat(disk) == VIR_STORAGE_FILE_NONE &&
6737 virDomainDiskGetType(disk) != VIR_STORAGE_TYPE_VOLUME)
6738 virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);
6740 /* default disk format for mirrored drive */
6741 if (disk->mirror &&
6742 disk->mirror->format == VIR_STORAGE_FILE_NONE)
6743 disk->mirror->format = VIR_STORAGE_FILE_RAW;
6745 if (qemuDomainDeviceDiskDefPostParseRestoreSecAlias(disk, qemuCaps,
6746 parseFlags) < 0)
6747 return -1;
6749 /* regenerate TLS alias for old status XMLs */
6750 if (parseFlags & VIR_DOMAIN_DEF_PARSE_STATUS &&
6751 disk->src->haveTLS == VIR_TRISTATE_BOOL_YES &&
6752 !disk->src->tlsAlias &&
6753 !(disk->src->tlsAlias = qemuAliasTLSObjFromSrcAlias(disk->info.alias)))
6754 return -1;
6756 return 0;
6760 static int
6761 qemuDomainDeviceNetDefPostParse(virDomainNetDefPtr net,
6762 const virDomainDef *def,
6763 virQEMUCapsPtr qemuCaps)
6765 if (net->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
6766 !net->model) {
6767 if (VIR_STRDUP(net->model,
6768 qemuDomainDefaultNetModel(def, qemuCaps)) < 0)
6769 return -1;
6772 return 0;
6776 static int
6777 qemuDomainDeviceVideoDefPostParse(virDomainVideoDefPtr video,
6778 const virDomainDef *def)
6780 if (video->type == VIR_DOMAIN_VIDEO_TYPE_DEFAULT) {
6781 if (ARCH_IS_PPC64(def->os.arch))
6782 video->type = VIR_DOMAIN_VIDEO_TYPE_VGA;
6783 else if (qemuDomainIsARMVirt(def) ||
6784 qemuDomainIsRISCVVirt(def) ||
6785 ARCH_IS_S390(def->os.arch))
6786 video->type = VIR_DOMAIN_VIDEO_TYPE_VIRTIO;
6787 else
6788 video->type = VIR_DOMAIN_VIDEO_TYPE_CIRRUS;
6791 if (video->type == VIR_DOMAIN_VIDEO_TYPE_QXL &&
6792 !video->vgamem) {
6793 video->vgamem = QEMU_QXL_VGAMEM_DEFAULT;
6796 return 0;
6800 static int
6801 qemuDomainDevicePanicDefPostParse(virDomainPanicDefPtr panic,
6802 const virDomainDef *def)
6804 if (panic->model == VIR_DOMAIN_PANIC_MODEL_DEFAULT) {
6805 if (qemuDomainIsPSeries(def))
6806 panic->model = VIR_DOMAIN_PANIC_MODEL_PSERIES;
6807 else if (ARCH_IS_S390(def->os.arch))
6808 panic->model = VIR_DOMAIN_PANIC_MODEL_S390;
6809 else
6810 panic->model = VIR_DOMAIN_PANIC_MODEL_ISA;
6813 return 0;
6817 static int
6818 qemuDomainVsockDefPostParse(virDomainVsockDefPtr vsock)
6820 if (vsock->model == VIR_DOMAIN_VSOCK_MODEL_DEFAULT)
6821 vsock->model = VIR_DOMAIN_VSOCK_MODEL_VIRTIO;
6823 return 0;
6827 static int
6828 qemuDomainHostdevDefMdevPostParse(virDomainHostdevSubsysMediatedDevPtr mdevsrc,
6829 virQEMUCapsPtr qemuCaps)
6831 /* QEMU 2.12 added support for vfio-pci display type, we default to
6832 * 'display=off' to stay safe from future changes */
6833 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VFIO_PCI_DISPLAY) &&
6834 mdevsrc->model == VIR_MDEV_MODEL_TYPE_VFIO_PCI &&
6835 mdevsrc->display == VIR_TRISTATE_SWITCH_ABSENT)
6836 mdevsrc->display = VIR_TRISTATE_SWITCH_OFF;
6838 return 0;
6842 static int
6843 qemuDomainHostdevDefPostParse(virDomainHostdevDefPtr hostdev,
6844 virQEMUCapsPtr qemuCaps)
6846 virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
6848 if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
6849 hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV &&
6850 qemuDomainHostdevDefMdevPostParse(&subsys->u.mdev, qemuCaps) < 0)
6851 return -1;
6853 return 0;
6857 static int
6858 qemuDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
6859 const virDomainDef *def,
6860 virCapsPtr caps ATTRIBUTE_UNUSED,
6861 unsigned int parseFlags,
6862 void *opaque,
6863 void *parseOpaque)
6865 virQEMUDriverPtr driver = opaque;
6866 /* Note that qemuCaps may be NULL when this function is called. This
6867 * function shall not fail in that case. It will be re-run on VM startup
6868 * with the capabilities populated. */
6869 virQEMUCapsPtr qemuCaps = parseOpaque;
6870 int ret = -1;
6872 switch ((virDomainDeviceType) dev->type) {
6873 case VIR_DOMAIN_DEVICE_NET:
6874 ret = qemuDomainDeviceNetDefPostParse(dev->data.net, def, qemuCaps);
6875 break;
6877 case VIR_DOMAIN_DEVICE_DISK:
6878 ret = qemuDomainDeviceDiskDefPostParse(dev->data.disk, qemuCaps,
6879 parseFlags);
6880 break;
6882 case VIR_DOMAIN_DEVICE_VIDEO:
6883 ret = qemuDomainDeviceVideoDefPostParse(dev->data.video, def);
6884 break;
6886 case VIR_DOMAIN_DEVICE_PANIC:
6887 ret = qemuDomainDevicePanicDefPostParse(dev->data.panic, def);
6888 break;
6890 case VIR_DOMAIN_DEVICE_CONTROLLER:
6891 ret = qemuDomainControllerDefPostParse(dev->data.controller, def,
6892 qemuCaps, parseFlags);
6893 break;
6895 case VIR_DOMAIN_DEVICE_SHMEM:
6896 ret = qemuDomainShmemDefPostParse(dev->data.shmem);
6897 break;
6899 case VIR_DOMAIN_DEVICE_CHR:
6900 ret = qemuDomainChrDefPostParse(dev->data.chr, def, driver, parseFlags);
6901 break;
6903 case VIR_DOMAIN_DEVICE_VSOCK:
6904 ret = qemuDomainVsockDefPostParse(dev->data.vsock);
6905 break;
6907 case VIR_DOMAIN_DEVICE_HOSTDEV:
6908 ret = qemuDomainHostdevDefPostParse(dev->data.hostdev, qemuCaps);
6909 break;
6911 case VIR_DOMAIN_DEVICE_LEASE:
6912 case VIR_DOMAIN_DEVICE_FS:
6913 case VIR_DOMAIN_DEVICE_INPUT:
6914 case VIR_DOMAIN_DEVICE_SOUND:
6915 case VIR_DOMAIN_DEVICE_WATCHDOG:
6916 case VIR_DOMAIN_DEVICE_GRAPHICS:
6917 case VIR_DOMAIN_DEVICE_HUB:
6918 case VIR_DOMAIN_DEVICE_REDIRDEV:
6919 case VIR_DOMAIN_DEVICE_SMARTCARD:
6920 case VIR_DOMAIN_DEVICE_MEMBALLOON:
6921 case VIR_DOMAIN_DEVICE_NVRAM:
6922 case VIR_DOMAIN_DEVICE_RNG:
6923 case VIR_DOMAIN_DEVICE_TPM:
6924 case VIR_DOMAIN_DEVICE_MEMORY:
6925 case VIR_DOMAIN_DEVICE_IOMMU:
6926 ret = 0;
6927 break;
6929 case VIR_DOMAIN_DEVICE_NONE:
6930 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6931 _("unexpected VIR_DOMAIN_DEVICE_NONE"));
6932 break;
6934 case VIR_DOMAIN_DEVICE_LAST:
6935 default:
6936 virReportEnumRangeError(virDomainDeviceType, dev->type);
6937 break;
6940 return ret;
6944 static int
6945 qemuDomainDefAssignAddresses(virDomainDef *def,
6946 virCapsPtr caps ATTRIBUTE_UNUSED,
6947 unsigned int parseFlags ATTRIBUTE_UNUSED,
6948 void *opaque,
6949 void *parseOpaque)
6951 virQEMUDriverPtr driver = opaque;
6952 /* Note that qemuCaps may be NULL when this function is called. This
6953 * function shall not fail in that case. It will be re-run on VM startup
6954 * with the capabilities populated. */
6955 virQEMUCapsPtr qemuCaps = parseOpaque;
6956 bool newDomain = parseFlags & VIR_DOMAIN_DEF_PARSE_ABI_UPDATE;
6958 /* Skip address assignment if @qemuCaps is not present. In such case devices
6959 * which are automatically added may be missing. Additionally @qemuCaps should
6960 * only be missing when reloading configs, thus addresses were already
6961 * assigned. */
6962 if (!qemuCaps)
6963 return 1;
6965 return qemuDomainAssignAddresses(def, qemuCaps, driver, NULL, newDomain);
6969 static int
6970 qemuDomainPostParseDataAlloc(const virDomainDef *def,
6971 virCapsPtr caps ATTRIBUTE_UNUSED,
6972 unsigned int parseFlags ATTRIBUTE_UNUSED,
6973 void *opaque,
6974 void **parseOpaque)
6976 virQEMUDriverPtr driver = opaque;
6978 if (!(*parseOpaque = virQEMUCapsCacheLookup(driver->qemuCapsCache,
6979 def->emulator)))
6980 return 1;
6982 return 0;
6986 static void
6987 qemuDomainPostParseDataFree(void *parseOpaque)
6989 virQEMUCapsPtr qemuCaps = parseOpaque;
6991 virObjectUnref(qemuCaps);
6995 virDomainDefParserConfig virQEMUDriverDomainDefParserConfig = {
6996 .domainPostParseBasicCallback = qemuDomainDefPostParseBasic,
6997 .domainPostParseDataAlloc = qemuDomainPostParseDataAlloc,
6998 .domainPostParseDataFree = qemuDomainPostParseDataFree,
6999 .devicesPostParseCallback = qemuDomainDeviceDefPostParse,
7000 .domainPostParseCallback = qemuDomainDefPostParse,
7001 .assignAddressesCallback = qemuDomainDefAssignAddresses,
7002 .domainValidateCallback = qemuDomainDefValidate,
7003 .deviceValidateCallback = qemuDomainDeviceDefValidate,
7005 .features = VIR_DOMAIN_DEF_FEATURE_MEMORY_HOTPLUG |
7006 VIR_DOMAIN_DEF_FEATURE_OFFLINE_VCPUPIN |
7007 VIR_DOMAIN_DEF_FEATURE_INDIVIDUAL_VCPUS |
7008 VIR_DOMAIN_DEF_FEATURE_USER_ALIAS |
7009 VIR_DOMAIN_DEF_FEATURE_FW_AUTOSELECT,
7013 static void
7014 qemuDomainObjSaveJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
7016 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
7018 if (virDomainObjIsActive(obj)) {
7019 if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, obj, driver->caps) < 0)
7020 VIR_WARN("Failed to save status on vm %s", obj->def->name);
7023 virObjectUnref(cfg);
7026 void
7027 qemuDomainObjSetJobPhase(virQEMUDriverPtr driver,
7028 virDomainObjPtr obj,
7029 int phase)
7031 qemuDomainObjPrivatePtr priv = obj->privateData;
7032 unsigned long long me = virThreadSelfID();
7034 if (!priv->job.asyncJob)
7035 return;
7037 VIR_DEBUG("Setting '%s' phase to '%s'",
7038 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7039 qemuDomainAsyncJobPhaseToString(priv->job.asyncJob, phase));
7041 if (priv->job.asyncOwner && me != priv->job.asyncOwner) {
7042 VIR_WARN("'%s' async job is owned by thread %llu",
7043 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7044 priv->job.asyncOwner);
7047 priv->job.phase = phase;
7048 priv->job.asyncOwner = me;
7049 qemuDomainObjSaveJob(driver, obj);
7052 void
7053 qemuDomainObjSetAsyncJobMask(virDomainObjPtr obj,
7054 unsigned long long allowedJobs)
7056 qemuDomainObjPrivatePtr priv = obj->privateData;
7058 if (!priv->job.asyncJob)
7059 return;
7061 priv->job.mask = allowedJobs | JOB_MASK(QEMU_JOB_DESTROY);
7064 void
7065 qemuDomainObjDiscardAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
7067 qemuDomainObjPrivatePtr priv = obj->privateData;
7069 if (priv->job.active == QEMU_JOB_ASYNC_NESTED)
7070 qemuDomainObjResetJob(priv);
7071 qemuDomainObjResetAsyncJob(priv);
7072 qemuDomainObjSaveJob(driver, obj);
7075 void
7076 qemuDomainObjReleaseAsyncJob(virDomainObjPtr obj)
7078 qemuDomainObjPrivatePtr priv = obj->privateData;
7080 VIR_DEBUG("Releasing ownership of '%s' async job",
7081 qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
7083 if (priv->job.asyncOwner != virThreadSelfID()) {
7084 VIR_WARN("'%s' async job is owned by thread %llu",
7085 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7086 priv->job.asyncOwner);
7088 priv->job.asyncOwner = 0;
7091 static bool
7092 qemuDomainNestedJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
7094 return !priv->job.asyncJob ||
7095 job == QEMU_JOB_NONE ||
7096 (priv->job.mask & JOB_MASK(job)) != 0;
7099 bool
7100 qemuDomainJobAllowed(qemuDomainObjPrivatePtr priv, qemuDomainJob job)
7102 return !priv->job.active && qemuDomainNestedJobAllowed(priv, job);
7105 static bool
7106 qemuDomainObjCanSetJob(qemuDomainObjPrivatePtr priv,
7107 qemuDomainJob job,
7108 qemuDomainAgentJob agentJob)
7110 return ((job == QEMU_JOB_NONE ||
7111 priv->job.active == QEMU_JOB_NONE) &&
7112 (agentJob == QEMU_AGENT_JOB_NONE ||
7113 priv->job.agentActive == QEMU_AGENT_JOB_NONE));
7116 /* Give up waiting for mutex after 30 seconds */
7117 #define QEMU_JOB_WAIT_TIME (1000ull * 30)
7120 * qemuDomainObjBeginJobInternal:
7121 * @driver: qemu driver
7122 * @obj: domain object
7123 * @job: qemuDomainJob to start
7124 * @asyncJob: qemuDomainAsyncJob to start
7125 * @nowait: don't wait trying to acquire @job
7127 * Acquires job for a domain object which must be locked before
7128 * calling. If there's already a job running waits up to
7129 * QEMU_JOB_WAIT_TIME after which the functions fails reporting
7130 * an error unless @nowait is set.
7132 * If @nowait is true this function tries to acquire job and if
7133 * it fails, then it returns immediately without waiting. No
7134 * error is reported in this case.
7136 * Returns: 0 on success,
7137 * -2 if unable to start job because of timeout or
7138 * maxQueuedJobs limit,
7139 * -1 otherwise.
7141 static int ATTRIBUTE_NONNULL(1)
7142 qemuDomainObjBeginJobInternal(virQEMUDriverPtr driver,
7143 virDomainObjPtr obj,
7144 qemuDomainJob job,
7145 qemuDomainAgentJob agentJob,
7146 qemuDomainAsyncJob asyncJob,
7147 bool nowait)
7149 qemuDomainObjPrivatePtr priv = obj->privateData;
7150 unsigned long long now;
7151 unsigned long long then;
7152 bool nested = job == QEMU_JOB_ASYNC_NESTED;
7153 bool async = job == QEMU_JOB_ASYNC;
7154 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
7155 const char *blocker = NULL;
7156 const char *agentBlocker = NULL;
7157 int ret = -1;
7158 unsigned long long duration = 0;
7159 unsigned long long agentDuration = 0;
7160 unsigned long long asyncDuration = 0;
7162 VIR_DEBUG("Starting job: job=%s agentJob=%s asyncJob=%s "
7163 "(vm=%p name=%s, current job=%s agentJob=%s async=%s)",
7164 qemuDomainJobTypeToString(job),
7165 qemuDomainAgentJobTypeToString(agentJob),
7166 qemuDomainAsyncJobTypeToString(asyncJob),
7167 obj, obj->def->name,
7168 qemuDomainJobTypeToString(priv->job.active),
7169 qemuDomainAgentJobTypeToString(priv->job.agentActive),
7170 qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
7172 if (virTimeMillisNow(&now) < 0) {
7173 virObjectUnref(cfg);
7174 return -1;
7177 priv->jobs_queued++;
7178 then = now + QEMU_JOB_WAIT_TIME;
7180 retry:
7181 if ((!async && job != QEMU_JOB_DESTROY) &&
7182 cfg->maxQueuedJobs &&
7183 priv->jobs_queued > cfg->maxQueuedJobs) {
7184 goto error;
7187 while (!nested && !qemuDomainNestedJobAllowed(priv, job)) {
7188 if (nowait)
7189 goto cleanup;
7191 VIR_DEBUG("Waiting for async job (vm=%p name=%s)", obj, obj->def->name);
7192 if (virCondWaitUntil(&priv->job.asyncCond, &obj->parent.lock, then) < 0)
7193 goto error;
7196 while (!qemuDomainObjCanSetJob(priv, job, agentJob)) {
7197 if (nowait)
7198 goto cleanup;
7200 VIR_DEBUG("Waiting for job (vm=%p name=%s)", obj, obj->def->name);
7201 if (virCondWaitUntil(&priv->job.cond, &obj->parent.lock, then) < 0)
7202 goto error;
7205 /* No job is active but a new async job could have been started while obj
7206 * was unlocked, so we need to recheck it. */
7207 if (!nested && !qemuDomainNestedJobAllowed(priv, job))
7208 goto retry;
7210 ignore_value(virTimeMillisNow(&now));
7212 if (job) {
7213 qemuDomainObjResetJob(priv);
7215 if (job != QEMU_JOB_ASYNC) {
7216 VIR_DEBUG("Started job: %s (async=%s vm=%p name=%s)",
7217 qemuDomainJobTypeToString(job),
7218 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7219 obj, obj->def->name);
7220 priv->job.active = job;
7221 priv->job.owner = virThreadSelfID();
7222 priv->job.ownerAPI = virThreadJobGet();
7223 priv->job.started = now;
7224 } else {
7225 VIR_DEBUG("Started async job: %s (vm=%p name=%s)",
7226 qemuDomainAsyncJobTypeToString(asyncJob),
7227 obj, obj->def->name);
7228 qemuDomainObjResetAsyncJob(priv);
7229 if (VIR_ALLOC(priv->job.current) < 0)
7230 goto cleanup;
7231 priv->job.current->status = QEMU_DOMAIN_JOB_STATUS_ACTIVE;
7232 priv->job.asyncJob = asyncJob;
7233 priv->job.asyncOwner = virThreadSelfID();
7234 priv->job.asyncOwnerAPI = virThreadJobGet();
7235 priv->job.asyncStarted = now;
7236 priv->job.current->started = now;
7240 if (agentJob) {
7241 qemuDomainObjResetAgentJob(priv);
7243 VIR_DEBUG("Started agent job: %s (vm=%p name=%s job=%s async=%s)",
7244 qemuDomainAgentJobTypeToString(agentJob),
7245 obj, obj->def->name,
7246 qemuDomainJobTypeToString(priv->job.active),
7247 qemuDomainAsyncJobTypeToString(priv->job.asyncJob));
7248 priv->job.agentActive = agentJob;
7249 priv->job.agentOwner = virThreadSelfID();
7250 priv->job.agentOwnerAPI = virThreadJobGet();
7251 priv->job.agentStarted = now;
7254 if (qemuDomainTrackJob(job))
7255 qemuDomainObjSaveJob(driver, obj);
7257 virObjectUnref(cfg);
7258 return 0;
7260 error:
7261 ignore_value(virTimeMillisNow(&now));
7262 if (priv->job.active && priv->job.started)
7263 duration = now - priv->job.started;
7264 if (priv->job.agentActive && priv->job.agentStarted)
7265 agentDuration = now - priv->job.agentStarted;
7266 if (priv->job.asyncJob && priv->job.asyncStarted)
7267 asyncDuration = now - priv->job.asyncStarted;
7269 VIR_WARN("Cannot start job (%s, %s, %s) for domain %s; "
7270 "current job is (%s, %s, %s) "
7271 "owned by (%llu %s, %llu %s, %llu %s (flags=0x%lx)) "
7272 "for (%llus, %llus, %llus)",
7273 qemuDomainJobTypeToString(job),
7274 qemuDomainAgentJobTypeToString(agentJob),
7275 qemuDomainAsyncJobTypeToString(asyncJob),
7276 obj->def->name,
7277 qemuDomainJobTypeToString(priv->job.active),
7278 qemuDomainAgentJobTypeToString(priv->job.agentActive),
7279 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7280 priv->job.owner, NULLSTR(priv->job.ownerAPI),
7281 priv->job.agentOwner, NULLSTR(priv->job.agentOwnerAPI),
7282 priv->job.asyncOwner, NULLSTR(priv->job.asyncOwnerAPI),
7283 priv->job.apiFlags,
7284 duration / 1000, agentDuration / 1000, asyncDuration / 1000);
7286 if (job) {
7287 if (nested || qemuDomainNestedJobAllowed(priv, job))
7288 blocker = priv->job.ownerAPI;
7289 else
7290 blocker = priv->job.asyncOwnerAPI;
7293 if (agentJob)
7294 agentBlocker = priv->job.agentOwnerAPI;
7296 if (errno == ETIMEDOUT) {
7297 if (blocker && agentBlocker) {
7298 virReportError(VIR_ERR_OPERATION_TIMEOUT,
7299 _("cannot acquire state change "
7300 "lock (held by monitor=%s agent=%s)"),
7301 blocker, agentBlocker);
7302 } else if (blocker) {
7303 virReportError(VIR_ERR_OPERATION_TIMEOUT,
7304 _("cannot acquire state change "
7305 "lock (held by monitor=%s)"),
7306 blocker);
7307 } else if (agentBlocker) {
7308 virReportError(VIR_ERR_OPERATION_TIMEOUT,
7309 _("cannot acquire state change "
7310 "lock (held by agent=%s)"),
7311 agentBlocker);
7312 } else {
7313 virReportError(VIR_ERR_OPERATION_TIMEOUT, "%s",
7314 _("cannot acquire state change lock"));
7316 ret = -2;
7317 } else if (cfg->maxQueuedJobs &&
7318 priv->jobs_queued > cfg->maxQueuedJobs) {
7319 if (blocker && agentBlocker) {
7320 virReportError(VIR_ERR_OPERATION_FAILED,
7321 _("cannot acquire state change "
7322 "lock (held by monitor=%s agent=%s) "
7323 "due to max_queued limit"),
7324 blocker, agentBlocker);
7325 } else if (blocker) {
7326 virReportError(VIR_ERR_OPERATION_FAILED,
7327 _("cannot acquire state change "
7328 "lock (held by monitor=%s) "
7329 "due to max_queued limit"),
7330 blocker);
7331 } else if (agentBlocker) {
7332 virReportError(VIR_ERR_OPERATION_FAILED,
7333 _("cannot acquire state change "
7334 "lock (held by agent=%s) "
7335 "due to max_queued limit"),
7336 agentBlocker);
7337 } else {
7338 virReportError(VIR_ERR_OPERATION_FAILED, "%s",
7339 _("cannot acquire state change lock "
7340 "due to max_queued limit"));
7342 ret = -2;
7343 } else {
7344 virReportSystemError(errno, "%s", _("cannot acquire job mutex"));
7347 cleanup:
7348 priv->jobs_queued--;
7349 virObjectUnref(cfg);
7350 return ret;
7354 * obj must be locked before calling
7356 * This must be called by anything that will change the VM state
7357 * in any way, or anything that will use the QEMU monitor.
7359 * Successful calls must be followed by EndJob eventually
7361 int qemuDomainObjBeginJob(virQEMUDriverPtr driver,
7362 virDomainObjPtr obj,
7363 qemuDomainJob job)
7365 if (qemuDomainObjBeginJobInternal(driver, obj, job,
7366 QEMU_AGENT_JOB_NONE,
7367 QEMU_ASYNC_JOB_NONE, false) < 0)
7368 return -1;
7369 else
7370 return 0;
7374 * qemuDomainObjBeginAgentJob:
7376 * Grabs agent type of job. Use if caller talks to guest agent only.
7378 * To end job call qemuDomainObjEndAgentJob.
7381 qemuDomainObjBeginAgentJob(virQEMUDriverPtr driver,
7382 virDomainObjPtr obj,
7383 qemuDomainAgentJob agentJob)
7385 return qemuDomainObjBeginJobInternal(driver, obj, QEMU_JOB_NONE,
7386 agentJob,
7387 QEMU_ASYNC_JOB_NONE, false);
7391 * qemuDomainObjBeginJobWithAgent:
7393 * Grabs both monitor and agent types of job. Use if caller talks to
7394 * both monitor and guest agent. However, if @job (or @agentJob) is
7395 * QEMU_JOB_NONE (or QEMU_AGENT_JOB_NONE) only agent job is acquired (or
7396 * monitor job).
7398 * To end job call qemuDomainObjEndJobWithAgent.
7401 qemuDomainObjBeginJobWithAgent(virQEMUDriverPtr driver,
7402 virDomainObjPtr obj,
7403 qemuDomainJob job,
7404 qemuDomainAgentJob agentJob)
7406 return qemuDomainObjBeginJobInternal(driver, obj, job, agentJob,
7407 QEMU_ASYNC_JOB_NONE, false);
7410 int qemuDomainObjBeginAsyncJob(virQEMUDriverPtr driver,
7411 virDomainObjPtr obj,
7412 qemuDomainAsyncJob asyncJob,
7413 virDomainJobOperation operation,
7414 unsigned long apiFlags)
7416 qemuDomainObjPrivatePtr priv;
7418 if (qemuDomainObjBeginJobInternal(driver, obj, QEMU_JOB_ASYNC,
7419 QEMU_AGENT_JOB_NONE,
7420 asyncJob, false) < 0)
7421 return -1;
7423 priv = obj->privateData;
7424 priv->job.current->operation = operation;
7425 priv->job.apiFlags = apiFlags;
7426 return 0;
7430 qemuDomainObjBeginNestedJob(virQEMUDriverPtr driver,
7431 virDomainObjPtr obj,
7432 qemuDomainAsyncJob asyncJob)
7434 qemuDomainObjPrivatePtr priv = obj->privateData;
7436 if (asyncJob != priv->job.asyncJob) {
7437 virReportError(VIR_ERR_INTERNAL_ERROR,
7438 _("unexpected async job %d type expected %d"),
7439 asyncJob, priv->job.asyncJob);
7440 return -1;
7443 if (priv->job.asyncOwner != virThreadSelfID()) {
7444 VIR_WARN("This thread doesn't seem to be the async job owner: %llu",
7445 priv->job.asyncOwner);
7448 return qemuDomainObjBeginJobInternal(driver, obj,
7449 QEMU_JOB_ASYNC_NESTED,
7450 QEMU_AGENT_JOB_NONE,
7451 QEMU_ASYNC_JOB_NONE,
7452 false);
7456 * qemuDomainObjBeginJobNowait:
7458 * @driver: qemu driver
7459 * @obj: domain object
7460 * @job: qemuDomainJob to start
7462 * Acquires job for a domain object which must be locked before
7463 * calling. If there's already a job running it returns
7464 * immediately without any error reported.
7466 * Returns: see qemuDomainObjBeginJobInternal
7469 qemuDomainObjBeginJobNowait(virQEMUDriverPtr driver,
7470 virDomainObjPtr obj,
7471 qemuDomainJob job)
7473 return qemuDomainObjBeginJobInternal(driver, obj, job,
7474 QEMU_AGENT_JOB_NONE,
7475 QEMU_ASYNC_JOB_NONE, true);
7479 * obj must be locked and have a reference before calling
7481 * To be called after completing the work associated with the
7482 * earlier qemuDomainBeginJob() call
7484 void
7485 qemuDomainObjEndJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
7487 qemuDomainObjPrivatePtr priv = obj->privateData;
7488 qemuDomainJob job = priv->job.active;
7490 priv->jobs_queued--;
7492 VIR_DEBUG("Stopping job: %s (async=%s vm=%p name=%s)",
7493 qemuDomainJobTypeToString(job),
7494 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7495 obj, obj->def->name);
7497 qemuDomainObjResetJob(priv);
7498 if (qemuDomainTrackJob(job))
7499 qemuDomainObjSaveJob(driver, obj);
7500 /* We indeed need to wake up ALL threads waiting because
7501 * grabbing a job requires checking more variables. */
7502 virCondBroadcast(&priv->job.cond);
7505 void
7506 qemuDomainObjEndAgentJob(virDomainObjPtr obj)
7508 qemuDomainObjPrivatePtr priv = obj->privateData;
7509 qemuDomainAgentJob agentJob = priv->job.agentActive;
7511 priv->jobs_queued--;
7513 VIR_DEBUG("Stopping agent job: %s (async=%s vm=%p name=%s)",
7514 qemuDomainAgentJobTypeToString(agentJob),
7515 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7516 obj, obj->def->name);
7518 qemuDomainObjResetAgentJob(priv);
7519 /* We indeed need to wake up ALL threads waiting because
7520 * grabbing a job requires checking more variables. */
7521 virCondBroadcast(&priv->job.cond);
7524 void
7525 qemuDomainObjEndJobWithAgent(virQEMUDriverPtr driver,
7526 virDomainObjPtr obj)
7528 qemuDomainObjPrivatePtr priv = obj->privateData;
7529 qemuDomainJob job = priv->job.active;
7530 qemuDomainAgentJob agentJob = priv->job.agentActive;
7532 priv->jobs_queued--;
7534 VIR_DEBUG("Stopping both jobs: %s %s (async=%s vm=%p name=%s)",
7535 qemuDomainJobTypeToString(job),
7536 qemuDomainAgentJobTypeToString(agentJob),
7537 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7538 obj, obj->def->name);
7540 qemuDomainObjResetJob(priv);
7541 qemuDomainObjResetAgentJob(priv);
7542 if (qemuDomainTrackJob(job))
7543 qemuDomainObjSaveJob(driver, obj);
7544 /* We indeed need to wake up ALL threads waiting because
7545 * grabbing a job requires checking more variables. */
7546 virCondBroadcast(&priv->job.cond);
7549 void
7550 qemuDomainObjEndAsyncJob(virQEMUDriverPtr driver, virDomainObjPtr obj)
7552 qemuDomainObjPrivatePtr priv = obj->privateData;
7554 priv->jobs_queued--;
7556 VIR_DEBUG("Stopping async job: %s (vm=%p name=%s)",
7557 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7558 obj, obj->def->name);
7560 qemuDomainObjResetAsyncJob(priv);
7561 qemuDomainObjSaveJob(driver, obj);
7562 virCondBroadcast(&priv->job.asyncCond);
7565 void
7566 qemuDomainObjAbortAsyncJob(virDomainObjPtr obj)
7568 qemuDomainObjPrivatePtr priv = obj->privateData;
7570 VIR_DEBUG("Requesting abort of async job: %s (vm=%p name=%s)",
7571 qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
7572 obj, obj->def->name);
7574 priv->job.abortJob = true;
7575 virDomainObjBroadcast(obj);
7579 * obj must be locked before calling
7581 * To be called immediately before any QEMU monitor API call
7582 * Must have already either called qemuDomainObjBeginJob() or
7583 * qemuDomainObjBeginJobWithAgent() and checked that the VM is
7584 * still active; may not be used for nested async jobs.
7586 * To be followed with qemuDomainObjExitMonitor() once complete
7588 static int
7589 qemuDomainObjEnterMonitorInternal(virQEMUDriverPtr driver,
7590 virDomainObjPtr obj,
7591 qemuDomainAsyncJob asyncJob)
7593 qemuDomainObjPrivatePtr priv = obj->privateData;
7595 if (asyncJob != QEMU_ASYNC_JOB_NONE) {
7596 int ret;
7597 if ((ret = qemuDomainObjBeginNestedJob(driver, obj, asyncJob)) < 0)
7598 return ret;
7599 if (!virDomainObjIsActive(obj)) {
7600 virReportError(VIR_ERR_OPERATION_FAILED, "%s",
7601 _("domain is no longer running"));
7602 qemuDomainObjEndJob(driver, obj);
7603 return -1;
7605 } else if (priv->job.asyncOwner == virThreadSelfID()) {
7606 VIR_WARN("This thread seems to be the async job owner; entering"
7607 " monitor without asking for a nested job is dangerous");
7610 VIR_DEBUG("Entering monitor (mon=%p vm=%p name=%s)",
7611 priv->mon, obj, obj->def->name);
7612 virObjectLock(priv->mon);
7613 virObjectRef(priv->mon);
7614 ignore_value(virTimeMillisNow(&priv->monStart));
7615 virObjectUnlock(obj);
7617 return 0;
7620 static void ATTRIBUTE_NONNULL(1)
7621 qemuDomainObjExitMonitorInternal(virQEMUDriverPtr driver,
7622 virDomainObjPtr obj)
7624 qemuDomainObjPrivatePtr priv = obj->privateData;
7625 bool hasRefs;
7627 hasRefs = virObjectUnref(priv->mon);
7629 if (hasRefs)
7630 virObjectUnlock(priv->mon);
7632 virObjectLock(obj);
7633 VIR_DEBUG("Exited monitor (mon=%p vm=%p name=%s)",
7634 priv->mon, obj, obj->def->name);
7636 priv->monStart = 0;
7637 if (!hasRefs)
7638 priv->mon = NULL;
7640 if (priv->job.active == QEMU_JOB_ASYNC_NESTED)
7641 qemuDomainObjEndJob(driver, obj);
7644 void qemuDomainObjEnterMonitor(virQEMUDriverPtr driver,
7645 virDomainObjPtr obj)
7647 ignore_value(qemuDomainObjEnterMonitorInternal(driver, obj,
7648 QEMU_ASYNC_JOB_NONE));
7651 /* obj must NOT be locked before calling
7653 * Should be paired with an earlier qemuDomainObjEnterMonitor() call
7655 * Returns -1 if the domain is no longer alive after exiting the monitor.
7656 * In that case, the caller should be careful when using obj's data,
7657 * e.g. the live definition in vm->def has been freed by qemuProcessStop
7658 * and replaced by the persistent definition, so pointers stolen
7659 * from the live definition could no longer be valid.
7661 int qemuDomainObjExitMonitor(virQEMUDriverPtr driver,
7662 virDomainObjPtr obj)
7664 qemuDomainObjExitMonitorInternal(driver, obj);
7665 if (!virDomainObjIsActive(obj)) {
7666 if (virGetLastErrorCode() == VIR_ERR_OK)
7667 virReportError(VIR_ERR_OPERATION_FAILED, "%s",
7668 _("domain is no longer running"));
7669 return -1;
7671 return 0;
7675 * obj must be locked before calling
7677 * To be called immediately before any QEMU monitor API call.
7678 * Must have already either called qemuDomainObjBeginJob()
7679 * and checked that the VM is still active, with asyncJob of
7680 * QEMU_ASYNC_JOB_NONE; or already called qemuDomainObjBeginAsyncJob,
7681 * with the same asyncJob.
7683 * Returns 0 if job was started, in which case this must be followed with
7684 * qemuDomainObjExitMonitor(); -2 if waiting for the nested job times out;
7685 * or -1 if the job could not be started (probably because the vm exited
7686 * in the meantime).
7689 qemuDomainObjEnterMonitorAsync(virQEMUDriverPtr driver,
7690 virDomainObjPtr obj,
7691 qemuDomainAsyncJob asyncJob)
7693 return qemuDomainObjEnterMonitorInternal(driver, obj, asyncJob);
7698 * obj must be locked before calling
7700 * To be called immediately before any QEMU agent API call.
7701 * Must have already called qemuDomainObjBeginAgentJob() or
7702 * qemuDomainObjBeginJobWithAgent() and checked that the VM is
7703 * still active.
7705 * To be followed with qemuDomainObjExitAgent() once complete
7707 qemuAgentPtr
7708 qemuDomainObjEnterAgent(virDomainObjPtr obj)
7710 qemuDomainObjPrivatePtr priv = obj->privateData;
7711 qemuAgentPtr agent = priv->agent;
7713 VIR_DEBUG("Entering agent (agent=%p vm=%p name=%s)",
7714 priv->agent, obj, obj->def->name);
7716 virObjectLock(agent);
7717 virObjectRef(agent);
7718 virObjectUnlock(obj);
7720 return agent;
7724 /* obj must NOT be locked before calling
7726 * Should be paired with an earlier qemuDomainObjEnterAgent() call
7728 void
7729 qemuDomainObjExitAgent(virDomainObjPtr obj, qemuAgentPtr agent)
7731 virObjectUnlock(agent);
7732 virObjectUnref(agent);
7733 virObjectLock(obj);
7735 VIR_DEBUG("Exited agent (agent=%p vm=%p name=%s)",
7736 agent, obj, obj->def->name);
7739 void qemuDomainObjEnterRemote(virDomainObjPtr obj)
7741 VIR_DEBUG("Entering remote (vm=%p name=%s)",
7742 obj, obj->def->name);
7743 virObjectUnlock(obj);
7748 qemuDomainObjExitRemote(virDomainObjPtr obj,
7749 bool checkActive)
7751 virObjectLock(obj);
7752 VIR_DEBUG("Exited remote (vm=%p name=%s)",
7753 obj, obj->def->name);
7755 if (checkActive && !virDomainObjIsActive(obj)) {
7756 virReportError(VIR_ERR_OPERATION_FAILED,
7757 _("domain '%s' is not running"),
7758 obj->def->name);
7759 return -1;
7762 return 0;
7766 static virDomainDefPtr
7767 qemuDomainDefFromXML(virQEMUDriverPtr driver,
7768 const char *xml)
7770 virCapsPtr caps;
7771 virDomainDefPtr def;
7773 if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
7774 return NULL;
7776 def = virDomainDefParseString(xml, caps, driver->xmlopt, NULL,
7777 VIR_DOMAIN_DEF_PARSE_INACTIVE |
7778 VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE);
7780 virObjectUnref(caps);
7781 return def;
7785 virDomainDefPtr
7786 qemuDomainDefCopy(virQEMUDriverPtr driver,
7787 virDomainDefPtr src,
7788 unsigned int flags)
7790 virDomainDefPtr ret = NULL;
7791 char *xml;
7793 if (!(xml = qemuDomainDefFormatXML(driver, src, flags)))
7794 return NULL;
7796 ret = qemuDomainDefFromXML(driver, xml);
7798 VIR_FREE(xml);
7799 return ret;
7803 static int
7804 qemuDomainDefFormatBufInternal(virQEMUDriverPtr driver,
7805 virDomainDefPtr def,
7806 virCPUDefPtr origCPU,
7807 unsigned int flags,
7808 virBuffer *buf)
7810 int ret = -1;
7811 virDomainDefPtr copy = NULL;
7812 virCapsPtr caps = NULL;
7813 virQEMUCapsPtr qemuCaps = NULL;
7815 virCheckFlags(VIR_DOMAIN_XML_COMMON_FLAGS | VIR_DOMAIN_XML_UPDATE_CPU, -1);
7817 if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
7818 goto cleanup;
7820 if (!(flags & (VIR_DOMAIN_XML_UPDATE_CPU | VIR_DOMAIN_XML_MIGRATABLE)))
7821 goto format;
7823 if (!(copy = virDomainDefCopy(def, caps, driver->xmlopt, NULL,
7824 flags & VIR_DOMAIN_XML_MIGRATABLE)))
7825 goto cleanup;
7827 def = copy;
7829 /* Update guest CPU requirements according to host CPU */
7830 if ((flags & VIR_DOMAIN_XML_UPDATE_CPU) &&
7831 def->cpu &&
7832 (def->cpu->mode != VIR_CPU_MODE_CUSTOM ||
7833 def->cpu->model)) {
7834 if (!(qemuCaps = virQEMUCapsCacheLookupCopy(driver->qemuCapsCache,
7835 def->emulator,
7836 def->os.machine)))
7837 goto cleanup;
7839 if (virCPUUpdate(def->os.arch, def->cpu,
7840 virQEMUCapsGetHostModel(qemuCaps, def->virtType,
7841 VIR_QEMU_CAPS_HOST_CPU_MIGRATABLE)) < 0)
7842 goto cleanup;
7845 if ((flags & VIR_DOMAIN_XML_MIGRATABLE)) {
7846 size_t i;
7847 int toremove = 0;
7848 virDomainControllerDefPtr usb = NULL, pci = NULL;
7850 /* If only the default USB controller is present, we can remove it
7851 * and make the XML compatible with older versions of libvirt which
7852 * didn't support USB controllers in the XML but always added the
7853 * default one to qemu anyway.
7855 for (i = 0; i < def->ncontrollers; i++) {
7856 if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_USB) {
7857 if (usb) {
7858 usb = NULL;
7859 break;
7861 usb = def->controllers[i];
7865 /* In order to maintain compatibility with version of libvirt that
7866 * didn't support <controller type='usb'/> (<= 0.9.4), we need to
7867 * drop the default USB controller, ie. a USB controller at index
7868 * zero with no model or with the default piix3-ohci model.
7870 * However, we only need to do so for x86 i440fx machine types,
7871 * because other architectures and machine types were introduced
7872 * when libvirt already supported <controller type='usb'/>.
7874 if (qemuDomainIsI440FX(def) &&
7875 usb && usb->idx == 0 &&
7876 (usb->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT ||
7877 usb->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI) &&
7878 !virDomainDeviceAliasIsUserAlias(usb->info.alias)) {
7879 VIR_DEBUG("Removing default USB controller from domain '%s'"
7880 " for migration compatibility", def->name);
7881 toremove++;
7882 } else {
7883 usb = NULL;
7886 /* Remove the default PCI controller if there is only one present
7887 * and its model is pci-root */
7888 for (i = 0; i < def->ncontrollers; i++) {
7889 if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
7890 if (pci) {
7891 pci = NULL;
7892 break;
7894 pci = def->controllers[i];
7898 if (pci && pci->idx == 0 &&
7899 pci->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT &&
7900 !virDomainDeviceAliasIsUserAlias(pci->info.alias) &&
7901 !pci->opts.pciopts.pcihole64) {
7902 VIR_DEBUG("Removing default pci-root from domain '%s'"
7903 " for migration compatibility", def->name);
7904 toremove++;
7905 } else {
7906 pci = NULL;
7909 if (toremove) {
7910 virDomainControllerDefPtr *controllers = def->controllers;
7911 int ncontrollers = def->ncontrollers;
7913 if (VIR_ALLOC_N(def->controllers, ncontrollers - toremove) < 0) {
7914 def->controllers = controllers;
7915 goto cleanup;
7918 def->ncontrollers = 0;
7919 for (i = 0; i < ncontrollers; i++) {
7920 if (controllers[i] != usb && controllers[i] != pci)
7921 def->controllers[def->ncontrollers++] = controllers[i];
7924 VIR_FREE(controllers);
7925 virDomainControllerDefFree(pci);
7926 virDomainControllerDefFree(usb);
7929 /* Remove the panic device for selected models if present */
7930 for (i = 0; i < def->npanics; i++) {
7931 if (def->panics[i]->model == VIR_DOMAIN_PANIC_MODEL_S390 ||
7932 def->panics[i]->model == VIR_DOMAIN_PANIC_MODEL_PSERIES) {
7933 VIR_DELETE_ELEMENT(def->panics, i, def->npanics);
7934 break;
7938 for (i = 0; i < def->nchannels; i++) {
7939 if (qemuDomainChrDefDropDefaultPath(def->channels[i], driver) < 0)
7940 goto cleanup;
7943 for (i = 0; i < def->nserials; i++) {
7944 virDomainChrDefPtr serial = def->serials[i];
7946 /* Historically, the native console type for some machine types
7947 * was not set at all, which means it defaulted to ISA even
7948 * though that was not even remotely accurate. To ensure migration
7949 * towards older libvirt versions works for such guests, we switch
7950 * it back to the default here */
7951 if (flags & VIR_DOMAIN_XML_MIGRATABLE) {
7952 switch ((virDomainChrSerialTargetType)serial->targetType) {
7953 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO:
7954 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM:
7955 serial->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE;
7956 serial->targetModel = VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_NONE;
7957 break;
7958 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA:
7959 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI:
7960 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB:
7961 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP:
7962 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE:
7963 case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST:
7964 /* Nothing to do */
7965 break;
7970 /* Replace the CPU definition updated according to QEMU with the one
7971 * used for starting the domain. The updated def will be sent
7972 * separately for backward compatibility.
7974 if (origCPU) {
7975 virCPUDefFree(def->cpu);
7976 if (!(def->cpu = virCPUDefCopy(origCPU)))
7977 goto cleanup;
7981 format:
7982 ret = virDomainDefFormatInternal(def, caps,
7983 virDomainDefFormatConvertXMLFlags(flags),
7984 buf, driver->xmlopt);
7986 cleanup:
7987 virDomainDefFree(copy);
7988 virObjectUnref(caps);
7989 virObjectUnref(qemuCaps);
7990 return ret;
7995 qemuDomainDefFormatBuf(virQEMUDriverPtr driver,
7996 virDomainDefPtr def,
7997 unsigned int flags,
7998 virBufferPtr buf)
8000 return qemuDomainDefFormatBufInternal(driver, def, NULL, flags, buf);
8004 static char *
8005 qemuDomainDefFormatXMLInternal(virQEMUDriverPtr driver,
8006 virDomainDefPtr def,
8007 virCPUDefPtr origCPU,
8008 unsigned int flags)
8010 virBuffer buf = VIR_BUFFER_INITIALIZER;
8012 if (qemuDomainDefFormatBufInternal(driver, def, origCPU, flags, &buf) < 0)
8013 return NULL;
8015 return virBufferContentAndReset(&buf);
8019 char *
8020 qemuDomainDefFormatXML(virQEMUDriverPtr driver,
8021 virDomainDefPtr def,
8022 unsigned int flags)
8024 return qemuDomainDefFormatXMLInternal(driver, def, NULL, flags);
8028 char *qemuDomainFormatXML(virQEMUDriverPtr driver,
8029 virDomainObjPtr vm,
8030 unsigned int flags)
8032 virDomainDefPtr def;
8033 qemuDomainObjPrivatePtr priv = vm->privateData;
8034 virCPUDefPtr origCPU = NULL;
8036 if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef) {
8037 def = vm->newDef;
8038 } else {
8039 def = vm->def;
8040 origCPU = priv->origCPU;
8043 return qemuDomainDefFormatXMLInternal(driver, def, origCPU, flags);
8046 char *
8047 qemuDomainDefFormatLive(virQEMUDriverPtr driver,
8048 virDomainDefPtr def,
8049 virCPUDefPtr origCPU,
8050 bool inactive,
8051 bool compatible)
8053 unsigned int flags = QEMU_DOMAIN_FORMAT_LIVE_FLAGS;
8055 if (inactive)
8056 flags |= VIR_DOMAIN_XML_INACTIVE;
8057 if (compatible)
8058 flags |= VIR_DOMAIN_XML_MIGRATABLE;
8060 return qemuDomainDefFormatXMLInternal(driver, def, origCPU, flags);
8064 void qemuDomainObjTaint(virQEMUDriverPtr driver,
8065 virDomainObjPtr obj,
8066 virDomainTaintFlags taint,
8067 qemuDomainLogContextPtr logCtxt)
8069 virErrorPtr orig_err = NULL;
8070 bool closeLog = false;
8071 char *timestamp = NULL;
8072 char uuidstr[VIR_UUID_STRING_BUFLEN];
8074 if (!virDomainObjTaint(obj, taint))
8075 return;
8077 virUUIDFormat(obj->def->uuid, uuidstr);
8079 VIR_WARN("Domain id=%d name='%s' uuid=%s is tainted: %s",
8080 obj->def->id,
8081 obj->def->name,
8082 uuidstr,
8083 virDomainTaintTypeToString(taint));
8085 /* We don't care about errors logging taint info, so
8086 * preserve original error, and clear any error that
8087 * is raised */
8088 orig_err = virSaveLastError();
8090 if (!(timestamp = virTimeStringNow()))
8091 goto cleanup;
8093 if (logCtxt == NULL) {
8094 logCtxt = qemuDomainLogContextNew(driver, obj,
8095 QEMU_DOMAIN_LOG_CONTEXT_MODE_ATTACH);
8096 if (!logCtxt) {
8097 VIR_WARN("Unable to open domainlog");
8098 goto cleanup;
8100 closeLog = true;
8103 if (qemuDomainLogContextWrite(logCtxt,
8104 "%s: Domain id=%d is tainted: %s\n",
8105 timestamp,
8106 obj->def->id,
8107 virDomainTaintTypeToString(taint)) < 0)
8108 virResetLastError();
8110 cleanup:
8111 VIR_FREE(timestamp);
8112 if (closeLog)
8113 virObjectUnref(logCtxt);
8114 if (orig_err) {
8115 virSetError(orig_err);
8116 virFreeError(orig_err);
8121 void qemuDomainObjCheckTaint(virQEMUDriverPtr driver,
8122 virDomainObjPtr obj,
8123 qemuDomainLogContextPtr logCtxt)
8125 size_t i;
8126 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8127 qemuDomainObjPrivatePtr priv = obj->privateData;
8129 if (virQEMUDriverIsPrivileged(driver) &&
8130 (!cfg->clearEmulatorCapabilities ||
8131 cfg->user == 0 ||
8132 cfg->group == 0))
8133 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES, logCtxt);
8135 if (priv->hookRun)
8136 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOOK, logCtxt);
8138 if (obj->def->namespaceData) {
8139 qemuDomainCmdlineDefPtr qemucmd = obj->def->namespaceData;
8140 if (qemucmd->num_args || qemucmd->num_env)
8141 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_ARGV, logCtxt);
8144 if (obj->def->cpu && obj->def->cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH)
8145 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HOST_CPU, logCtxt);
8147 for (i = 0; i < obj->def->ndisks; i++)
8148 qemuDomainObjCheckDiskTaint(driver, obj, obj->def->disks[i], logCtxt);
8150 for (i = 0; i < obj->def->nhostdevs; i++)
8151 qemuDomainObjCheckHostdevTaint(driver, obj, obj->def->hostdevs[i],
8152 logCtxt);
8154 for (i = 0; i < obj->def->nnets; i++)
8155 qemuDomainObjCheckNetTaint(driver, obj, obj->def->nets[i], logCtxt);
8157 if (obj->def->os.dtb)
8158 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CUSTOM_DTB, logCtxt);
8160 virObjectUnref(cfg);
8164 void qemuDomainObjCheckDiskTaint(virQEMUDriverPtr driver,
8165 virDomainObjPtr obj,
8166 virDomainDiskDefPtr disk,
8167 qemuDomainLogContextPtr logCtxt)
8169 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8171 if (disk->rawio == VIR_TRISTATE_BOOL_YES)
8172 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES,
8173 logCtxt);
8175 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
8176 virStorageSourceGetActualType(disk->src) == VIR_STORAGE_TYPE_BLOCK &&
8177 disk->src->path && virFileIsCDROM(disk->src->path) == 1)
8178 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_CDROM_PASSTHROUGH,
8179 logCtxt);
8181 virObjectUnref(cfg);
8185 void qemuDomainObjCheckHostdevTaint(virQEMUDriverPtr driver,
8186 virDomainObjPtr obj,
8187 virDomainHostdevDefPtr hostdev,
8188 qemuDomainLogContextPtr logCtxt)
8190 if (!virHostdevIsSCSIDevice(hostdev))
8191 return;
8193 if (hostdev->source.subsys.u.scsi.rawio == VIR_TRISTATE_BOOL_YES)
8194 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_HIGH_PRIVILEGES, logCtxt);
8198 void qemuDomainObjCheckNetTaint(virQEMUDriverPtr driver,
8199 virDomainObjPtr obj,
8200 virDomainNetDefPtr net,
8201 qemuDomainLogContextPtr logCtxt)
8203 /* script is only useful for NET_TYPE_ETHERNET (qemu) and
8204 * NET_TYPE_BRIDGE (xen), but could be (incorrectly) specified for
8205 * any interface type. In any case, it's adding user sauce into
8206 * the soup, so it should taint the domain.
8208 if (net->script != NULL)
8209 qemuDomainObjTaint(driver, obj, VIR_DOMAIN_TAINT_SHELL_SCRIPTS, logCtxt);
8213 qemuDomainLogContextPtr qemuDomainLogContextNew(virQEMUDriverPtr driver,
8214 virDomainObjPtr vm,
8215 qemuDomainLogContextMode mode)
8217 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8218 qemuDomainLogContextPtr ctxt = NULL;
8220 if (qemuDomainInitialize() < 0)
8221 goto cleanup;
8223 if (!(ctxt = virObjectNew(qemuDomainLogContextClass)))
8224 goto cleanup;
8226 VIR_DEBUG("Context new %p stdioLogD=%d", ctxt, cfg->stdioLogD);
8227 ctxt->writefd = -1;
8228 ctxt->readfd = -1;
8230 if (virAsprintf(&ctxt->path, "%s/%s.log", cfg->logDir, vm->def->name) < 0)
8231 goto error;
8233 if (cfg->stdioLogD) {
8234 ctxt->manager = virLogManagerNew(virQEMUDriverIsPrivileged(driver));
8235 if (!ctxt->manager)
8236 goto error;
8238 ctxt->writefd = virLogManagerDomainOpenLogFile(ctxt->manager,
8239 "qemu",
8240 vm->def->uuid,
8241 vm->def->name,
8242 ctxt->path,
8244 &ctxt->inode,
8245 &ctxt->pos);
8246 if (ctxt->writefd < 0)
8247 goto error;
8248 } else {
8249 if ((ctxt->writefd = open(ctxt->path, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)) < 0) {
8250 virReportSystemError(errno, _("failed to create logfile %s"),
8251 ctxt->path);
8252 goto error;
8254 if (virSetCloseExec(ctxt->writefd) < 0) {
8255 virReportSystemError(errno, _("failed to set close-on-exec flag on %s"),
8256 ctxt->path);
8257 goto error;
8260 /* For unprivileged startup we must truncate the file since
8261 * we can't rely on logrotate. We don't use O_TRUNC since
8262 * it is better for SELinux policy if we truncate afterwards */
8263 if (mode == QEMU_DOMAIN_LOG_CONTEXT_MODE_START &&
8264 !virQEMUDriverIsPrivileged(driver) &&
8265 ftruncate(ctxt->writefd, 0) < 0) {
8266 virReportSystemError(errno, _("failed to truncate %s"),
8267 ctxt->path);
8268 goto error;
8271 if (mode == QEMU_DOMAIN_LOG_CONTEXT_MODE_START) {
8272 if ((ctxt->readfd = open(ctxt->path, O_RDONLY, S_IRUSR | S_IWUSR)) < 0) {
8273 virReportSystemError(errno, _("failed to open logfile %s"),
8274 ctxt->path);
8275 goto error;
8277 if (virSetCloseExec(ctxt->readfd) < 0) {
8278 virReportSystemError(errno, _("failed to set close-on-exec flag on %s"),
8279 ctxt->path);
8280 goto error;
8284 if ((ctxt->pos = lseek(ctxt->writefd, 0, SEEK_END)) < 0) {
8285 virReportSystemError(errno, _("failed to seek in log file %s"),
8286 ctxt->path);
8287 goto error;
8291 cleanup:
8292 virObjectUnref(cfg);
8293 return ctxt;
8295 error:
8296 virObjectUnref(ctxt);
8297 ctxt = NULL;
8298 goto cleanup;
8302 int qemuDomainLogContextWrite(qemuDomainLogContextPtr ctxt,
8303 const char *fmt, ...)
8305 va_list argptr;
8306 char *message = NULL;
8307 int ret = -1;
8309 va_start(argptr, fmt);
8311 if (virVasprintf(&message, fmt, argptr) < 0)
8312 goto cleanup;
8313 if (!ctxt->manager &&
8314 lseek(ctxt->writefd, 0, SEEK_END) < 0) {
8315 virReportSystemError(errno, "%s",
8316 _("Unable to seek to end of domain logfile"));
8317 goto cleanup;
8319 if (safewrite(ctxt->writefd, message, strlen(message)) < 0) {
8320 virReportSystemError(errno, "%s",
8321 _("Unable to write to domain logfile"));
8322 goto cleanup;
8325 ret = 0;
8327 cleanup:
8328 va_end(argptr);
8329 VIR_FREE(message);
8330 return ret;
8334 ssize_t qemuDomainLogContextRead(qemuDomainLogContextPtr ctxt,
8335 char **msg)
8337 VIR_DEBUG("Context read %p manager=%p inode=%llu pos=%llu",
8338 ctxt, ctxt->manager,
8339 (unsigned long long)ctxt->inode,
8340 (unsigned long long)ctxt->pos);
8341 char *buf;
8342 size_t buflen;
8343 if (ctxt->manager) {
8344 buf = virLogManagerDomainReadLogFile(ctxt->manager,
8345 ctxt->path,
8346 ctxt->inode,
8347 ctxt->pos,
8348 1024 * 128,
8350 if (!buf)
8351 return -1;
8352 buflen = strlen(buf);
8353 } else {
8354 ssize_t got;
8356 buflen = 1024 * 128;
8358 /* Best effort jump to start of messages */
8359 ignore_value(lseek(ctxt->readfd, ctxt->pos, SEEK_SET));
8361 if (VIR_ALLOC_N(buf, buflen) < 0)
8362 return -1;
8364 got = saferead(ctxt->readfd, buf, buflen - 1);
8365 if (got < 0) {
8366 VIR_FREE(buf);
8367 virReportSystemError(errno, "%s",
8368 _("Unable to read from log file"));
8369 return -1;
8372 buf[got] = '\0';
8374 ignore_value(VIR_REALLOC_N_QUIET(buf, got + 1));
8375 buflen = got;
8378 *msg = buf;
8380 return buflen;
8385 * qemuDomainLogAppendMessage:
8387 * This is a best-effort attempt to add a log message to the qemu log file
8388 * either by using virtlogd or the legacy approach */
8390 qemuDomainLogAppendMessage(virQEMUDriverPtr driver,
8391 virDomainObjPtr vm,
8392 const char *fmt,
8393 ...)
8395 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8396 virLogManagerPtr manager = NULL;
8397 va_list ap;
8398 char *path = NULL;
8399 int writefd = -1;
8400 char *message = NULL;
8401 int ret = -1;
8403 va_start(ap, fmt);
8405 if (virVasprintf(&message, fmt, ap) < 0)
8406 goto cleanup;
8408 VIR_DEBUG("Append log message (vm='%s' message='%s) stdioLogD=%d",
8409 vm->def->name, message, cfg->stdioLogD);
8411 if (virAsprintf(&path, "%s/%s.log", cfg->logDir, vm->def->name) < 0)
8412 goto cleanup;
8414 if (cfg->stdioLogD) {
8415 if (!(manager = virLogManagerNew(virQEMUDriverIsPrivileged(driver))))
8416 goto cleanup;
8418 if (virLogManagerDomainAppendMessage(manager, "qemu", vm->def->uuid,
8419 vm->def->name, path, message, 0) < 0)
8420 goto cleanup;
8421 } else {
8422 if ((writefd = open(path, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)) < 0) {
8423 virReportSystemError(errno, _("failed to create logfile %s"),
8424 path);
8425 goto cleanup;
8428 if (safewrite(writefd, message, strlen(message)) < 0)
8429 goto cleanup;
8432 ret = 0;
8434 cleanup:
8435 va_end(ap);
8436 VIR_FREE(message);
8437 VIR_FORCE_CLOSE(writefd);
8438 virLogManagerFree(manager);
8439 virObjectUnref(cfg);
8440 VIR_FREE(path);
8442 return ret;
8446 int qemuDomainLogContextGetWriteFD(qemuDomainLogContextPtr ctxt)
8448 return ctxt->writefd;
8452 void qemuDomainLogContextMarkPosition(qemuDomainLogContextPtr ctxt)
8454 if (ctxt->manager)
8455 virLogManagerDomainGetLogFilePosition(ctxt->manager,
8456 ctxt->path,
8458 &ctxt->inode,
8459 &ctxt->pos);
8460 else
8461 ctxt->pos = lseek(ctxt->writefd, 0, SEEK_END);
8465 virLogManagerPtr qemuDomainLogContextGetManager(qemuDomainLogContextPtr ctxt)
8467 return ctxt->manager;
8471 /* Locate an appropriate 'qemu-img' binary. */
8472 const char *
8473 qemuFindQemuImgBinary(virQEMUDriverPtr driver)
8475 if (!driver->qemuImgBinary)
8476 virReportError(VIR_ERR_INTERNAL_ERROR,
8477 "%s", _("unable to find qemu-img"));
8479 return driver->qemuImgBinary;
8483 qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
8484 virDomainMomentObjPtr snapshot,
8485 virCapsPtr caps,
8486 virDomainXMLOptionPtr xmlopt,
8487 const char *snapshotDir)
8489 char *newxml = NULL;
8490 int ret = -1;
8491 char *snapDir = NULL;
8492 char *snapFile = NULL;
8493 char uuidstr[VIR_UUID_STRING_BUFLEN];
8494 unsigned int flags = VIR_DOMAIN_SNAPSHOT_FORMAT_SECURE |
8495 VIR_DOMAIN_SNAPSHOT_FORMAT_INTERNAL;
8496 virDomainSnapshotDefPtr def = virDomainSnapshotObjGetDef(snapshot);
8498 if (virDomainSnapshotGetCurrent(vm->snapshots) == snapshot)
8499 flags |= VIR_DOMAIN_SNAPSHOT_FORMAT_CURRENT;
8500 virUUIDFormat(vm->def->uuid, uuidstr);
8501 newxml = virDomainSnapshotDefFormat(uuidstr, def, caps, xmlopt, flags);
8502 if (newxml == NULL)
8503 return -1;
8505 if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0)
8506 goto cleanup;
8507 if (virFileMakePath(snapDir) < 0) {
8508 virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
8509 snapDir);
8510 goto cleanup;
8513 if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, def->common.name) < 0)
8514 goto cleanup;
8516 ret = virXMLSaveFile(snapFile, NULL, "snapshot-edit", newxml);
8518 cleanup:
8519 VIR_FREE(snapFile);
8520 VIR_FREE(snapDir);
8521 VIR_FREE(newxml);
8522 return ret;
8526 qemuDomainCheckpointWriteMetadata(virDomainObjPtr vm,
8527 virDomainMomentObjPtr checkpoint,
8528 virCapsPtr caps,
8529 virDomainXMLOptionPtr xmlopt,
8530 const char *checkpointDir)
8532 unsigned int flags = VIR_DOMAIN_CHECKPOINT_FORMAT_SECURE |
8533 VIR_DOMAIN_CHECKPOINT_FORMAT_INTERNAL;
8534 virDomainCheckpointDefPtr def = virDomainCheckpointObjGetDef(checkpoint);
8535 VIR_AUTOFREE(char *) newxml = NULL;
8536 VIR_AUTOFREE(char *) chkDir = NULL;
8537 VIR_AUTOFREE(char *) chkFile = NULL;
8539 if (virDomainCheckpointGetCurrent(vm->checkpoints) == checkpoint)
8540 flags |= VIR_DOMAIN_CHECKPOINT_FORMAT_CURRENT;
8541 newxml = virDomainCheckpointDefFormat(def, caps, xmlopt, flags);
8542 if (newxml == NULL)
8543 return -1;
8545 if (virAsprintf(&chkDir, "%s/%s", checkpointDir, vm->def->name) < 0)
8546 return -1;
8547 if (virFileMakePath(chkDir) < 0) {
8548 virReportSystemError(errno, _("cannot create checkpoint directory '%s'"),
8549 chkDir);
8550 return -1;
8553 if (virAsprintf(&chkFile, "%s/%s.xml", chkDir, def->common.name) < 0)
8554 return -1;
8556 return virXMLSaveFile(chkFile, NULL, "checkpoint-edit", newxml);
8559 /* The domain is expected to be locked and inactive. Return -1 on normal
8560 * failure, 1 if we skipped a disk due to try_all. */
8561 static int
8562 qemuDomainSnapshotForEachQcow2Raw(virQEMUDriverPtr driver,
8563 virDomainDefPtr def,
8564 const char *name,
8565 const char *op,
8566 bool try_all,
8567 int ndisks)
8569 const char *qemuimgarg[] = { NULL, "snapshot", NULL, NULL, NULL, NULL };
8570 size_t i;
8571 bool skipped = false;
8573 qemuimgarg[0] = qemuFindQemuImgBinary(driver);
8574 if (qemuimgarg[0] == NULL) {
8575 /* qemuFindQemuImgBinary set the error */
8576 return -1;
8579 qemuimgarg[2] = op;
8580 qemuimgarg[3] = name;
8582 for (i = 0; i < ndisks; i++) {
8583 /* FIXME: we also need to handle LVM here */
8584 if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
8585 int format = virDomainDiskGetFormat(def->disks[i]);
8587 if (format > 0 && format != VIR_STORAGE_FILE_QCOW2) {
8588 if (try_all) {
8589 /* Continue on even in the face of error, since other
8590 * disks in this VM may have the same snapshot name.
8592 VIR_WARN("skipping snapshot action on %s",
8593 def->disks[i]->dst);
8594 skipped = true;
8595 continue;
8596 } else if (STREQ(op, "-c") && i) {
8597 /* We must roll back partial creation by deleting
8598 * all earlier snapshots. */
8599 qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
8600 "-d", false, i);
8602 virReportError(VIR_ERR_OPERATION_INVALID,
8603 _("Disk device '%s' does not support"
8604 " snapshotting"),
8605 def->disks[i]->dst);
8606 return -1;
8609 qemuimgarg[4] = virDomainDiskGetSource(def->disks[i]);
8611 if (virRun(qemuimgarg, NULL) < 0) {
8612 if (try_all) {
8613 VIR_WARN("skipping snapshot action on %s",
8614 def->disks[i]->dst);
8615 skipped = true;
8616 continue;
8617 } else if (STREQ(op, "-c") && i) {
8618 /* We must roll back partial creation by deleting
8619 * all earlier snapshots. */
8620 qemuDomainSnapshotForEachQcow2Raw(driver, def, name,
8621 "-d", false, i);
8623 return -1;
8628 return skipped ? 1 : 0;
8631 /* The domain is expected to be locked and inactive. Return -1 on normal
8632 * failure, 1 if we skipped a disk due to try_all. */
8634 qemuDomainSnapshotForEachQcow2(virQEMUDriverPtr driver,
8635 virDomainObjPtr vm,
8636 virDomainMomentObjPtr snap,
8637 const char *op,
8638 bool try_all)
8640 /* Prefer action on the disks in use at the time the snapshot was
8641 * created; but fall back to current definition if dealing with a
8642 * snapshot created prior to libvirt 0.9.5. */
8643 virDomainDefPtr def = snap->def->dom;
8645 if (!def)
8646 def = vm->def;
8647 return qemuDomainSnapshotForEachQcow2Raw(driver, def, snap->def->name,
8648 op, try_all, def->ndisks);
8651 /* Discard one snapshot (or its metadata), without reparenting any children. */
8653 qemuDomainSnapshotDiscard(virQEMUDriverPtr driver,
8654 virDomainObjPtr vm,
8655 virDomainMomentObjPtr snap,
8656 bool update_parent,
8657 bool metadata_only)
8659 char *snapFile = NULL;
8660 int ret = -1;
8661 qemuDomainObjPrivatePtr priv;
8662 virDomainMomentObjPtr parentsnap = NULL;
8663 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8665 if (!metadata_only) {
8666 if (!virDomainObjIsActive(vm)) {
8667 /* Ignore any skipped disks */
8668 if (qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-d",
8669 true) < 0)
8670 goto cleanup;
8671 } else {
8672 priv = vm->privateData;
8673 qemuDomainObjEnterMonitor(driver, vm);
8674 /* we continue on even in the face of error */
8675 qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
8676 ignore_value(qemuDomainObjExitMonitor(driver, vm));
8680 if (virAsprintf(&snapFile, "%s/%s/%s.xml", cfg->snapshotDir,
8681 vm->def->name, snap->def->name) < 0)
8682 goto cleanup;
8684 if (snap == virDomainSnapshotGetCurrent(vm->snapshots)) {
8685 virDomainSnapshotSetCurrent(vm->snapshots, NULL);
8686 if (update_parent && snap->def->parent) {
8687 parentsnap = virDomainSnapshotFindByName(vm->snapshots,
8688 snap->def->parent);
8689 if (!parentsnap) {
8690 VIR_WARN("missing parent snapshot matching name '%s'",
8691 snap->def->parent);
8692 } else {
8693 virDomainSnapshotSetCurrent(vm->snapshots, parentsnap);
8694 if (qemuDomainSnapshotWriteMetadata(vm, parentsnap, driver->caps,
8695 driver->xmlopt,
8696 cfg->snapshotDir) < 0) {
8697 VIR_WARN("failed to set parent snapshot '%s' as current",
8698 snap->def->parent);
8699 virDomainSnapshotSetCurrent(vm->snapshots, NULL);
8705 if (unlink(snapFile) < 0)
8706 VIR_WARN("Failed to unlink %s", snapFile);
8707 if (update_parent)
8708 virDomainMomentDropParent(snap);
8709 virDomainSnapshotObjListRemove(vm->snapshots, snap);
8711 ret = 0;
8713 cleanup:
8714 VIR_FREE(snapFile);
8715 virObjectUnref(cfg);
8716 return ret;
8719 /* Hash iterator callback to discard multiple snapshots. */
8720 int qemuDomainMomentDiscardAll(void *payload,
8721 const void *name ATTRIBUTE_UNUSED,
8722 void *data)
8724 virDomainMomentObjPtr moment = payload;
8725 virQEMUMomentRemovePtr curr = data;
8726 int err;
8728 if (!curr->found && curr->current == moment)
8729 curr->found = true;
8730 err = curr->momentDiscard(curr->driver, curr->vm, moment, false,
8731 curr->metadata_only);
8732 if (err && !curr->err)
8733 curr->err = err;
8734 return 0;
8738 qemuDomainSnapshotDiscardAllMetadata(virQEMUDriverPtr driver,
8739 virDomainObjPtr vm)
8741 virQEMUMomentRemove rem = {
8742 .driver = driver,
8743 .vm = vm,
8744 .metadata_only = true
8747 virDomainSnapshotForEach(vm->snapshots, qemuDomainMomentDiscardAll, &rem);
8748 virDomainSnapshotObjListRemoveAll(vm->snapshots);
8750 return rem.err;
8754 /* Discard one checkpoint (or its metadata), without reparenting any children. */
8756 qemuDomainCheckpointDiscard(virQEMUDriverPtr driver,
8757 virDomainObjPtr vm,
8758 virDomainMomentObjPtr chk,
8759 bool update_parent,
8760 bool metadata_only)
8762 char *chkFile = NULL;
8763 int ret = -1;
8764 virDomainMomentObjPtr parentchk = NULL;
8765 virDomainCheckpointDefPtr parentdef = NULL;
8766 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8767 size_t i, j;
8768 virJSONValuePtr arr = NULL;
8770 if (!metadata_only && !virDomainObjIsActive(vm)) {
8771 virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
8772 _("cannot remove checkpoint from inactive domain"));
8773 goto cleanup;
8776 if (virAsprintf(&chkFile, "%s/%s/%s.xml", cfg->checkpointDir,
8777 vm->def->name, chk->def->name) < 0)
8778 goto cleanup;
8780 if (chk->def->parent) {
8781 parentchk = virDomainCheckpointFindByName(vm->checkpoints,
8782 chk->def->parent);
8783 if (!parentchk) {
8784 VIR_WARN("missing parent checkpoint matching name '%s'",
8785 chk->def->parent);
8787 parentdef = virDomainCheckpointObjGetDef(parentchk);
8790 if (!metadata_only) {
8791 qemuDomainObjPrivatePtr priv = vm->privateData;
8792 bool success = true;
8793 virDomainCheckpointDefPtr chkdef = virDomainCheckpointObjGetDef(chk);
8795 if (qemuBlockNodeNamesDetect(driver, vm, QEMU_ASYNC_JOB_NONE) < 0)
8796 goto cleanup;
8797 qemuDomainObjEnterMonitor(driver, vm);
8798 for (i = 0; i < chkdef->ndisks; i++) {
8799 virDomainCheckpointDiskDef *disk = &chkdef->disks[i];
8800 const char *node;
8802 if (disk->type != VIR_DOMAIN_CHECKPOINT_TYPE_BITMAP)
8803 continue;
8805 node = qemuBlockNodeLookup(vm, disk->name);
8806 if (parentchk) {
8807 arr = virJSONValueNewArray();
8808 if (!arr ||
8809 virJSONValueArrayAppendString(arr, disk->bitmap) < 0) {
8810 success = false;
8811 break;
8814 for (j = 0; j < parentdef->ndisks; j++) {
8815 virDomainCheckpointDiskDef *disk2;
8817 disk2 = &parentdef->disks[j];
8818 if (STRNEQ(disk->name, disk2->name))
8819 continue;
8820 if (chk == virDomainCheckpointGetCurrent(vm->checkpoints) &&
8821 qemuMonitorEnableBitmap(priv->mon, node,
8822 disk2->bitmap) < 0) {
8823 success = false;
8824 break;
8826 if (qemuMonitorMergeBitmaps(priv->mon, node,
8827 disk2->bitmap, &arr) < 0) {
8828 success = false;
8829 break;
8833 if (qemuMonitorDeleteBitmap(priv->mon, node, disk->bitmap) < 0) {
8834 success = false;
8835 break;
8838 if (qemuDomainObjExitMonitor(driver, vm) < 0 || !success)
8839 goto cleanup;
8842 if (chk == virDomainCheckpointGetCurrent(vm->checkpoints)) {
8843 virDomainCheckpointSetCurrent(vm->checkpoints, NULL);
8844 if (update_parent && parentchk) {
8845 virDomainCheckpointSetCurrent(vm->checkpoints, parentchk);
8846 if (qemuDomainCheckpointWriteMetadata(vm, parentchk, driver->caps,
8847 driver->xmlopt,
8848 cfg->checkpointDir) < 0) {
8849 VIR_WARN("failed to set parent checkpoint '%s' as current",
8850 chk->def->parent);
8851 virDomainCheckpointSetCurrent(vm->checkpoints, NULL);
8856 if (unlink(chkFile) < 0)
8857 VIR_WARN("Failed to unlink %s", chkFile);
8858 if (update_parent)
8859 virDomainMomentDropParent(chk);
8860 virDomainCheckpointObjListRemove(vm->checkpoints, chk);
8862 ret = 0;
8864 cleanup:
8865 VIR_FREE(chkFile);
8866 virObjectUnref(cfg);
8867 virJSONValueFree(arr);
8868 return ret;
8872 qemuDomainCheckpointDiscardAllMetadata(virQEMUDriverPtr driver,
8873 virDomainObjPtr vm)
8875 virQEMUMomentRemove rem;
8877 rem.driver = driver;
8878 rem.vm = vm;
8879 rem.metadata_only = true;
8880 rem.err = 0;
8881 virDomainCheckpointForEach(vm->checkpoints, qemuDomainMomentDiscardAll,
8882 &rem);
8883 virDomainCheckpointObjListRemoveAll(vm->checkpoints);
8885 return rem.err;
8889 static void
8890 qemuDomainRemoveInactiveCommon(virQEMUDriverPtr driver,
8891 virDomainObjPtr vm)
8893 virQEMUDriverConfigPtr cfg;
8894 VIR_AUTOFREE(char *) snapDir = NULL;
8895 VIR_AUTOFREE(char *) chkDir = NULL;
8897 cfg = virQEMUDriverGetConfig(driver);
8899 /* Remove any snapshot metadata prior to removing the domain */
8900 if (qemuDomainSnapshotDiscardAllMetadata(driver, vm) < 0) {
8901 VIR_WARN("unable to remove all snapshots for domain %s",
8902 vm->def->name);
8903 } else if (virAsprintf(&snapDir, "%s/%s", cfg->snapshotDir,
8904 vm->def->name) < 0) {
8905 VIR_WARN("unable to remove snapshot directory %s/%s",
8906 cfg->snapshotDir, vm->def->name);
8907 } else if (rmdir(snapDir) < 0 && errno != ENOENT) {
8908 VIR_WARN("unable to remove snapshot directory %s", snapDir);
8910 /* Remove any checkpoint metadata prior to removing the domain */
8911 if (qemuDomainCheckpointDiscardAllMetadata(driver, vm) < 0) {
8912 VIR_WARN("unable to remove all checkpoints for domain %s",
8913 vm->def->name);
8914 } else if (virAsprintf(&chkDir, "%s/%s", cfg->checkpointDir,
8915 vm->def->name) < 0) {
8916 VIR_WARN("unable to remove checkpoint directory %s/%s",
8917 cfg->snapshotDir, vm->def->name);
8918 } else if (rmdir(chkDir) < 0 && errno != ENOENT) {
8919 VIR_WARN("unable to remove checkpoint directory %s", chkDir);
8921 qemuExtDevicesCleanupHost(driver, vm->def);
8923 virObjectUnref(cfg);
8928 * qemuDomainRemoveInactive:
8930 * The caller must hold a lock to the vm.
8932 void
8933 qemuDomainRemoveInactive(virQEMUDriverPtr driver,
8934 virDomainObjPtr vm)
8936 if (vm->persistent) {
8937 /* Short-circuit, we don't want to remove a persistent domain */
8938 return;
8941 qemuDomainRemoveInactiveCommon(driver, vm);
8943 virDomainObjListRemove(driver->domains, vm);
8948 * qemuDomainRemoveInactiveLocked:
8950 * The caller must hold a lock to the vm and must hold the
8951 * lock on driver->domains in order to call the remove obj
8952 * from locked list method.
8954 static void
8955 qemuDomainRemoveInactiveLocked(virQEMUDriverPtr driver,
8956 virDomainObjPtr vm)
8958 if (vm->persistent) {
8959 /* Short-circuit, we don't want to remove a persistent domain */
8960 return;
8963 qemuDomainRemoveInactiveCommon(driver, vm);
8965 virDomainObjListRemoveLocked(driver->domains, vm);
8970 * qemuDomainRemoveInactiveJob:
8972 * Just like qemuDomainRemoveInactive but it tries to grab a
8973 * QEMU_JOB_MODIFY first. Even though it doesn't succeed in
8974 * grabbing the job the control carries with
8975 * qemuDomainRemoveInactive call.
8977 void
8978 qemuDomainRemoveInactiveJob(virQEMUDriverPtr driver,
8979 virDomainObjPtr vm)
8981 bool haveJob;
8983 haveJob = qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) >= 0;
8985 qemuDomainRemoveInactive(driver, vm);
8987 if (haveJob)
8988 qemuDomainObjEndJob(driver, vm);
8993 * qemuDomainRemoveInactiveJobLocked:
8995 * Similar to qemuDomainRemoveInactiveJob, except that the caller must
8996 * also hold the lock @driver->domains
8998 void
8999 qemuDomainRemoveInactiveJobLocked(virQEMUDriverPtr driver,
9000 virDomainObjPtr vm)
9002 bool haveJob;
9004 haveJob = qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) >= 0;
9006 qemuDomainRemoveInactiveLocked(driver, vm);
9008 if (haveJob)
9009 qemuDomainObjEndJob(driver, vm);
9013 void
9014 qemuDomainSetFakeReboot(virQEMUDriverPtr driver,
9015 virDomainObjPtr vm,
9016 bool value)
9018 qemuDomainObjPrivatePtr priv = vm->privateData;
9019 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
9021 if (priv->fakeReboot == value)
9022 goto cleanup;
9024 priv->fakeReboot = value;
9026 if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0)
9027 VIR_WARN("Failed to save status on vm %s", vm->def->name);
9029 cleanup:
9030 virObjectUnref(cfg);
9033 static void
9034 qemuDomainCheckRemoveOptionalDisk(virQEMUDriverPtr driver,
9035 virDomainObjPtr vm,
9036 size_t diskIndex)
9038 char uuid[VIR_UUID_STRING_BUFLEN];
9039 virObjectEventPtr event = NULL;
9040 virDomainDiskDefPtr disk = vm->def->disks[diskIndex];
9041 const char *src = virDomainDiskGetSource(disk);
9043 virUUIDFormat(vm->def->uuid, uuid);
9045 VIR_DEBUG("Dropping disk '%s' on domain '%s' (UUID '%s') "
9046 "due to inaccessible source '%s'",
9047 disk->dst, vm->def->name, uuid, src);
9049 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM ||
9050 disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
9052 event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
9053 disk->info.alias,
9054 VIR_DOMAIN_EVENT_DISK_CHANGE_MISSING_ON_START);
9055 virDomainDiskEmptySource(disk);
9056 /* keeping the old startup policy would be invalid for new images */
9057 disk->startupPolicy = VIR_DOMAIN_STARTUP_POLICY_DEFAULT;
9058 } else {
9059 event = virDomainEventDiskChangeNewFromObj(vm, src, NULL,
9060 disk->info.alias,
9061 VIR_DOMAIN_EVENT_DISK_DROP_MISSING_ON_START);
9062 virDomainDiskRemove(vm->def, diskIndex);
9063 virDomainDiskDefFree(disk);
9066 virObjectEventStateQueue(driver->domainEventState, event);
9071 * qemuDomainCheckDiskStartupPolicy:
9072 * @driver: qemu driver object
9073 * @vm: domain object
9074 * @disk: index of disk to check
9075 * @cold_boot: true if a new VM is being started
9077 * This function should be called when the source storage for a disk device is
9078 * missing. The function checks whether the startup policy for the disk allows
9079 * removal of the source (or disk) according to the state of the VM.
9081 * The function returns 0 if the source or disk was dropped and -1 if the state
9082 * of the VM does not allow this. This function does not report errors, but
9083 * clears any reported error if 0 is returned.
9086 qemuDomainCheckDiskStartupPolicy(virQEMUDriverPtr driver,
9087 virDomainObjPtr vm,
9088 size_t diskIndex,
9089 bool cold_boot)
9091 int startupPolicy = vm->def->disks[diskIndex]->startupPolicy;
9092 int device = vm->def->disks[diskIndex]->device;
9094 switch ((virDomainStartupPolicy) startupPolicy) {
9095 case VIR_DOMAIN_STARTUP_POLICY_OPTIONAL:
9096 /* Once started with an optional disk, qemu saves its section
9097 * in the migration stream, so later, when restoring from it
9098 * we must make sure the sections match. */
9099 if (!cold_boot &&
9100 device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
9101 device != VIR_DOMAIN_DISK_DEVICE_CDROM)
9102 return -1;
9103 break;
9105 case VIR_DOMAIN_STARTUP_POLICY_DEFAULT:
9106 case VIR_DOMAIN_STARTUP_POLICY_MANDATORY:
9107 return -1;
9109 case VIR_DOMAIN_STARTUP_POLICY_REQUISITE:
9110 if (cold_boot)
9111 return -1;
9112 break;
9114 case VIR_DOMAIN_STARTUP_POLICY_LAST:
9115 /* this should never happen */
9116 break;
9119 qemuDomainCheckRemoveOptionalDisk(driver, vm, diskIndex);
9120 virResetLastError();
9121 return 0;
9127 * The vm must be locked when any of the following cleanup functions is
9128 * called.
9131 qemuDomainCleanupAdd(virDomainObjPtr vm,
9132 qemuDomainCleanupCallback cb)
9134 qemuDomainObjPrivatePtr priv = vm->privateData;
9135 size_t i;
9137 VIR_DEBUG("vm=%s, cb=%p", vm->def->name, cb);
9139 for (i = 0; i < priv->ncleanupCallbacks; i++) {
9140 if (priv->cleanupCallbacks[i] == cb)
9141 return 0;
9144 if (VIR_RESIZE_N(priv->cleanupCallbacks,
9145 priv->ncleanupCallbacks_max,
9146 priv->ncleanupCallbacks, 1) < 0)
9147 return -1;
9149 priv->cleanupCallbacks[priv->ncleanupCallbacks++] = cb;
9150 return 0;
9153 void
9154 qemuDomainCleanupRemove(virDomainObjPtr vm,
9155 qemuDomainCleanupCallback cb)
9157 qemuDomainObjPrivatePtr priv = vm->privateData;
9158 size_t i;
9160 VIR_DEBUG("vm=%s, cb=%p", vm->def->name, cb);
9162 for (i = 0; i < priv->ncleanupCallbacks; i++) {
9163 if (priv->cleanupCallbacks[i] == cb)
9164 VIR_DELETE_ELEMENT_INPLACE(priv->cleanupCallbacks,
9165 i, priv->ncleanupCallbacks);
9168 VIR_SHRINK_N(priv->cleanupCallbacks,
9169 priv->ncleanupCallbacks_max,
9170 priv->ncleanupCallbacks_max - priv->ncleanupCallbacks);
9173 void
9174 qemuDomainCleanupRun(virQEMUDriverPtr driver,
9175 virDomainObjPtr vm)
9177 qemuDomainObjPrivatePtr priv = vm->privateData;
9178 size_t i;
9180 VIR_DEBUG("driver=%p, vm=%s", driver, vm->def->name);
9182 /* run cleanup callbacks in reverse order */
9183 for (i = 0; i < priv->ncleanupCallbacks; i++) {
9184 if (priv->cleanupCallbacks[priv->ncleanupCallbacks - (i + 1)])
9185 priv->cleanupCallbacks[i](driver, vm);
9188 VIR_FREE(priv->cleanupCallbacks);
9189 priv->ncleanupCallbacks = 0;
9190 priv->ncleanupCallbacks_max = 0;
9193 static void
9194 qemuDomainGetImageIds(virQEMUDriverConfigPtr cfg,
9195 virDomainObjPtr vm,
9196 virStorageSourcePtr src,
9197 virStorageSourcePtr parentSrc,
9198 uid_t *uid, gid_t *gid)
9200 virSecurityLabelDefPtr vmlabel;
9201 virSecurityDeviceLabelDefPtr disklabel;
9203 if (uid)
9204 *uid = -1;
9205 if (gid)
9206 *gid = -1;
9208 if (cfg) {
9209 if (uid)
9210 *uid = cfg->user;
9212 if (gid)
9213 *gid = cfg->group;
9216 if (vm && (vmlabel = virDomainDefGetSecurityLabelDef(vm->def, "dac")) &&
9217 vmlabel->label)
9218 virParseOwnershipIds(vmlabel->label, uid, gid);
9220 if (parentSrc &&
9221 (disklabel = virStorageSourceGetSecurityLabelDef(parentSrc, "dac")) &&
9222 disklabel->label)
9223 virParseOwnershipIds(disklabel->label, uid, gid);
9225 if ((disklabel = virStorageSourceGetSecurityLabelDef(src, "dac")) &&
9226 disklabel->label)
9227 virParseOwnershipIds(disklabel->label, uid, gid);
9232 qemuDomainStorageFileInit(virQEMUDriverPtr driver,
9233 virDomainObjPtr vm,
9234 virStorageSourcePtr src,
9235 virStorageSourcePtr parent)
9237 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
9238 uid_t uid;
9239 gid_t gid;
9240 int ret = -1;
9242 qemuDomainGetImageIds(cfg, vm, src, parent, &uid, &gid);
9244 if (virStorageFileInitAs(src, uid, gid) < 0)
9245 goto cleanup;
9247 ret = 0;
9249 cleanup:
9250 virObjectUnref(cfg);
9251 return ret;
9255 char *
9256 qemuDomainStorageAlias(const char *device, int depth)
9258 char *alias;
9260 device = qemuAliasDiskDriveSkipPrefix(device);
9262 if (!depth)
9263 ignore_value(VIR_STRDUP(alias, device));
9264 else
9265 ignore_value(virAsprintf(&alias, "%s.%d", device, depth));
9266 return alias;
9271 * qemuDomainDetermineDiskChain:
9272 * @driver: qemu driver object
9273 * @vm: domain object
9274 * @disk: disk definition
9275 * @disksrc: source to determine the chain for, may be NULL
9276 * @report_broken: report broken chain verbosely
9278 * Prepares and initializes the backing chain of disk @disk. In cases where
9279 * a new source is to be associated with @disk the @disksrc parameter can be
9280 * used to override the source. If @report_broken is true missing images
9281 * in the backing chain are reported.
9284 qemuDomainDetermineDiskChain(virQEMUDriverPtr driver,
9285 virDomainObjPtr vm,
9286 virDomainDiskDefPtr disk,
9287 virStorageSourcePtr disksrc,
9288 bool report_broken)
9290 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
9291 virStorageSourcePtr src; /* iterator for the backing chain declared in XML */
9292 virStorageSourcePtr n; /* iterator for the backing chain detected from disk */
9293 qemuDomainObjPrivatePtr priv = vm->privateData;
9294 int ret = -1;
9295 uid_t uid;
9296 gid_t gid;
9298 if (!disksrc)
9299 disksrc = disk->src;
9301 if (virStorageSourceIsEmpty(disksrc)) {
9302 ret = 0;
9303 goto cleanup;
9306 /* There is no need to check the backing chain for disks without backing
9307 * support */
9308 if (virStorageSourceIsLocalStorage(disksrc) &&
9309 disksrc->format > VIR_STORAGE_FILE_NONE &&
9310 disksrc->format < VIR_STORAGE_FILE_BACKING) {
9312 if (!virFileExists(disksrc->path)) {
9313 if (report_broken)
9314 virStorageFileReportBrokenChain(errno, disksrc, disksrc);
9316 goto cleanup;
9319 /* terminate the chain for such images as the code below would do */
9320 if (!disksrc->backingStore &&
9321 !(disksrc->backingStore = virStorageSourceNew()))
9322 goto cleanup;
9324 /* host cdrom requires special treatment in qemu, so we need to check
9325 * whether a block device is a cdrom */
9326 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
9327 disksrc->format == VIR_STORAGE_FILE_RAW &&
9328 virStorageSourceIsBlockLocal(disksrc) &&
9329 virFileIsCDROM(disksrc->path) == 1)
9330 disksrc->hostcdrom = true;
9332 ret = 0;
9333 goto cleanup;
9336 src = disksrc;
9337 /* skip to the end of the chain if there is any */
9338 while (virStorageSourceHasBacking(src)) {
9339 if (report_broken) {
9340 int rv = virStorageFileSupportsAccess(src);
9342 if (rv < 0)
9343 goto cleanup;
9345 if (rv > 0) {
9346 if (qemuDomainStorageFileInit(driver, vm, src, disksrc) < 0)
9347 goto cleanup;
9349 if (virStorageFileAccess(src, F_OK) < 0) {
9350 virStorageFileReportBrokenChain(errno, src, disksrc);
9351 virStorageFileDeinit(src);
9352 goto cleanup;
9355 virStorageFileDeinit(src);
9358 src = src->backingStore;
9361 /* We skipped to the end of the chain. Skip detection if there's the
9362 * terminator. (An allocated but empty backingStore) */
9363 if (src->backingStore) {
9364 ret = 0;
9365 goto cleanup;
9368 qemuDomainGetImageIds(cfg, vm, src, disksrc, &uid, &gid);
9370 if (virStorageFileGetMetadata(src, uid, gid, report_broken) < 0)
9371 goto cleanup;
9373 for (n = src->backingStore; virStorageSourceIsBacking(n); n = n->backingStore) {
9374 if (qemuDomainValidateStorageSource(n, priv->qemuCaps) < 0)
9375 goto cleanup;
9377 if (qemuDomainPrepareDiskSourceData(disk, n, cfg, priv->qemuCaps) < 0)
9378 goto cleanup;
9380 if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV) &&
9381 qemuDomainPrepareStorageSourceBlockdev(disk, n, priv, cfg) < 0)
9382 goto cleanup;
9385 ret = 0;
9387 cleanup:
9388 virObjectUnref(cfg);
9389 return ret;
9394 * qemuDomainDiskGetBackendAlias:
9395 * @disk: disk definition
9396 * @qemuCaps: emulator capabilities
9397 * @backendAlias: filled with the alias of the disk storage backend
9399 * Returns the correct alias for the disk backend. This may be the alias of
9400 * -drive for legacy setup or the correct node name for -blockdev setups.
9402 * @backendAlias may be NULL on success if the backend does not exist
9403 * (disk is empty). Caller is responsible for freeing @backendAlias.
9405 * Returns 0 on success, -1 on error with libvirt error reported.
9408 qemuDomainDiskGetBackendAlias(virDomainDiskDefPtr disk,
9409 virQEMUCapsPtr qemuCaps,
9410 char **backendAlias)
9412 qemuDomainDiskPrivatePtr priv = QEMU_DOMAIN_DISK_PRIVATE(disk);
9413 const char *nodename = NULL;
9414 *backendAlias = NULL;
9416 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKDEV)) {
9417 if (!(*backendAlias = qemuAliasDiskDriveFromDisk(disk)))
9418 return -1;
9420 return 0;
9423 if (virStorageSourceIsEmpty(disk->src))
9424 return 0;
9426 if (disk->copy_on_read == VIR_TRISTATE_SWITCH_ON)
9427 nodename = priv->nodeCopyOnRead;
9428 else
9429 nodename = disk->src->nodeformat;
9431 if (VIR_STRDUP(*backendAlias, nodename) < 0)
9432 return -1;
9434 return 0;
9439 * qemuDomainDiskChainElementRevoke:
9441 * Revoke access to a single backing chain element. This restores the labels,
9442 * removes cgroup ACLs for devices and removes locks.
9444 void
9445 qemuDomainDiskChainElementRevoke(virQEMUDriverPtr driver,
9446 virDomainObjPtr vm,
9447 virStorageSourcePtr elem)
9449 if (qemuTeardownImageCgroup(vm, elem) < 0)
9450 VIR_WARN("Failed to teardown cgroup for disk path %s",
9451 NULLSTR(elem->path));
9453 if (qemuSecurityRestoreImageLabel(driver, vm, elem, false) < 0)
9454 VIR_WARN("Unable to restore security label on %s", NULLSTR(elem->path));
9456 if (qemuDomainNamespaceTeardownDisk(vm, elem) < 0)
9457 VIR_WARN("Unable to remove /dev entry for %s", NULLSTR(elem->path));
9459 if (virDomainLockImageDetach(driver->lockManager, vm, elem) < 0)
9460 VIR_WARN("Unable to release lock on %s", NULLSTR(elem->path));
9465 * qemuDomainDiskChainElementPrepare:
9466 * @driver: qemu driver data
9467 * @vm: domain object
9468 * @elem: source structure to set access for
9469 * @readonly: setup read-only access if true
9470 * @newSource: @elem describes a storage source which @vm can't access yet
9472 * Allow a VM access to a single element of a disk backing chain; this helper
9473 * ensures that the lock manager, cgroup device controller, and security manager
9474 * labelling are all aware of each new file before it is added to a chain.
9476 * When modifying permissions of @elem which @vm can already access (is in the
9477 * backing chain) @newSource needs to be set to false.
9480 qemuDomainDiskChainElementPrepare(virQEMUDriverPtr driver,
9481 virDomainObjPtr vm,
9482 virStorageSourcePtr elem,
9483 bool readonly,
9484 bool newSource)
9486 bool was_readonly = elem->readonly;
9487 virQEMUDriverConfigPtr cfg = NULL;
9488 int ret = -1;
9490 cfg = virQEMUDriverGetConfig(driver);
9492 elem->readonly = readonly;
9494 if (virDomainLockImageAttach(driver->lockManager, cfg->uri, vm, elem) < 0)
9495 goto cleanup;
9497 if (newSource &&
9498 qemuDomainNamespaceSetupDisk(vm, elem) < 0)
9499 goto cleanup;
9501 if (qemuSetupImageCgroup(vm, elem) < 0)
9502 goto cleanup;
9504 if (qemuSecuritySetImageLabel(driver, vm, elem, false) < 0)
9505 goto cleanup;
9507 ret = 0;
9509 cleanup:
9510 elem->readonly = was_readonly;
9511 virObjectUnref(cfg);
9512 return ret;
9517 * Makes sure the @disk differs from @orig_disk only by the source
9518 * path and nothing else. Fields that are being checked and the
9519 * information whether they are nullable (may not be specified) or is
9520 * taken from the virDomainDiskDefFormat() code.
9522 bool
9523 qemuDomainDiskChangeSupported(virDomainDiskDefPtr disk,
9524 virDomainDiskDefPtr orig_disk)
9526 #define CHECK_EQ(field, field_name, nullable) \
9527 do { \
9528 if (nullable && !disk->field) \
9529 break; \
9530 if (disk->field != orig_disk->field) { \
9531 virReportError(VIR_ERR_OPERATION_UNSUPPORTED, \
9532 _("cannot modify field '%s' of the disk"), \
9533 field_name); \
9534 return false; \
9536 } while (0)
9538 CHECK_EQ(device, "device", false);
9539 CHECK_EQ(bus, "bus", false);
9540 if (STRNEQ(disk->dst, orig_disk->dst)) {
9541 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9542 _("cannot modify field '%s' of the disk"),
9543 "target");
9544 return false;
9546 CHECK_EQ(tray_status, "tray", true);
9547 CHECK_EQ(removable, "removable", true);
9549 if (disk->geometry.cylinders &&
9550 disk->geometry.heads &&
9551 disk->geometry.sectors) {
9552 CHECK_EQ(geometry.cylinders, "geometry cylinders", false);
9553 CHECK_EQ(geometry.heads, "geometry heads", false);
9554 CHECK_EQ(geometry.sectors, "geometry sectors", false);
9555 CHECK_EQ(geometry.trans, "BIOS-translation-modus", true);
9558 CHECK_EQ(blockio.logical_block_size,
9559 "blockio logical_block_size", false);
9560 CHECK_EQ(blockio.physical_block_size,
9561 "blockio physical_block_size", false);
9563 CHECK_EQ(blkdeviotune.total_bytes_sec,
9564 "blkdeviotune total_bytes_sec",
9565 true);
9566 CHECK_EQ(blkdeviotune.read_bytes_sec,
9567 "blkdeviotune read_bytes_sec",
9568 true);
9569 CHECK_EQ(blkdeviotune.write_bytes_sec,
9570 "blkdeviotune write_bytes_sec",
9571 true);
9572 CHECK_EQ(blkdeviotune.total_iops_sec,
9573 "blkdeviotune total_iops_sec",
9574 true);
9575 CHECK_EQ(blkdeviotune.read_iops_sec,
9576 "blkdeviotune read_iops_sec",
9577 true);
9578 CHECK_EQ(blkdeviotune.write_iops_sec,
9579 "blkdeviotune write_iops_sec",
9580 true);
9581 CHECK_EQ(blkdeviotune.total_bytes_sec_max,
9582 "blkdeviotune total_bytes_sec_max",
9583 true);
9584 CHECK_EQ(blkdeviotune.read_bytes_sec_max,
9585 "blkdeviotune read_bytes_sec_max",
9586 true);
9587 CHECK_EQ(blkdeviotune.write_bytes_sec_max,
9588 "blkdeviotune write_bytes_sec_max",
9589 true);
9590 CHECK_EQ(blkdeviotune.total_iops_sec_max,
9591 "blkdeviotune total_iops_sec_max",
9592 true);
9593 CHECK_EQ(blkdeviotune.read_iops_sec_max,
9594 "blkdeviotune read_iops_sec_max",
9595 true);
9596 CHECK_EQ(blkdeviotune.write_iops_sec_max,
9597 "blkdeviotune write_iops_sec_max",
9598 true);
9599 CHECK_EQ(blkdeviotune.size_iops_sec,
9600 "blkdeviotune size_iops_sec",
9601 true);
9602 CHECK_EQ(blkdeviotune.group_name,
9603 "blkdeviotune group_name",
9604 true);
9606 if (disk->serial && STRNEQ_NULLABLE(disk->serial, orig_disk->serial)) {
9607 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9608 _("cannot modify field '%s' of the disk"),
9609 "serial");
9610 return false;
9613 if (disk->wwn && STRNEQ_NULLABLE(disk->wwn, orig_disk->wwn)) {
9614 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9615 _("cannot modify field '%s' of the disk"),
9616 "wwn");
9617 return false;
9620 if (disk->vendor && STRNEQ_NULLABLE(disk->vendor, orig_disk->vendor)) {
9621 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9622 _("cannot modify field '%s' of the disk"),
9623 "vendor");
9624 return false;
9627 if (disk->product && STRNEQ_NULLABLE(disk->product, orig_disk->product)) {
9628 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9629 _("cannot modify field '%s' of the disk"),
9630 "product");
9631 return false;
9634 CHECK_EQ(cachemode, "cache", true);
9635 CHECK_EQ(error_policy, "error_policy", true);
9636 CHECK_EQ(rerror_policy, "rerror_policy", true);
9637 CHECK_EQ(iomode, "io", true);
9638 CHECK_EQ(ioeventfd, "ioeventfd", true);
9639 CHECK_EQ(event_idx, "event_idx", true);
9640 CHECK_EQ(copy_on_read, "copy_on_read", true);
9641 /* "snapshot" is a libvirt internal field and thus can be changed */
9642 /* startupPolicy is allowed to be updated. Therefore not checked here. */
9643 CHECK_EQ(transient, "transient", true);
9645 /* Note: For some address types the address auto generation for
9646 * @disk has still not happened at this point (e.g. driver
9647 * specific addresses) therefore we can't catch these possible
9648 * address modifications here. */
9649 if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
9650 !virDomainDeviceInfoAddressIsEqual(&disk->info, &orig_disk->info)) {
9651 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9652 _("cannot modify field '%s' of the disk"),
9653 "address");
9654 return false;
9657 /* device alias is checked already in virDomainDefCompatibleDevice */
9659 CHECK_EQ(info.bootIndex, "boot order", true);
9660 CHECK_EQ(rawio, "rawio", true);
9661 CHECK_EQ(sgio, "sgio", true);
9662 CHECK_EQ(discard, "discard", true);
9663 CHECK_EQ(iothread, "iothread", true);
9665 if (disk->domain_name &&
9666 STRNEQ_NULLABLE(disk->domain_name, orig_disk->domain_name)) {
9667 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9668 _("cannot modify field '%s' of the disk"),
9669 "backenddomain");
9670 return false;
9673 /* checks for fields stored in disk->src */
9674 /* unfortunately 'readonly' and 'shared' can't be converted to tristate
9675 * values thus we need to ignore the check if the new value is 'false' */
9676 CHECK_EQ(src->readonly, "readonly", true);
9677 CHECK_EQ(src->shared, "shared", true);
9679 if (!virStoragePRDefIsEqual(disk->src->pr,
9680 orig_disk->src->pr)) {
9681 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9682 _("cannot modify field '%s' of the disk"),
9683 "reservations");
9684 return false;
9687 #undef CHECK_EQ
9689 return true;
9692 bool
9693 qemuDomainDiskBlockJobIsActive(virDomainDiskDefPtr disk)
9695 qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
9697 if (disk->mirror) {
9698 virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
9699 _("disk '%s' already in active block job"),
9700 disk->dst);
9702 return true;
9705 if (diskPriv->blockjob &&
9706 qemuBlockJobIsRunning(diskPriv->blockjob)) {
9707 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
9708 _("disk '%s' already in active block job"),
9709 disk->dst);
9710 return true;
9713 return false;
9718 * qemuDomainHasBlockjob:
9719 * @vm: domain object
9720 * @copy_only: Reject only block copy job
9722 * Return true if @vm has at least one disk involved in a current block
9723 * copy/commit/pull job. If @copy_only is true this returns true only if the
9724 * disk is involved in a block copy.
9725 * */
9726 bool
9727 qemuDomainHasBlockjob(virDomainObjPtr vm,
9728 bool copy_only)
9730 size_t i;
9731 for (i = 0; i < vm->def->ndisks; i++) {
9732 virDomainDiskDefPtr disk = vm->def->disks[i];
9733 qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
9735 if (!copy_only && diskPriv->blockjob &&
9736 qemuBlockJobIsRunning(diskPriv->blockjob))
9737 return true;
9739 if (disk->mirror && disk->mirrorJob == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY)
9740 return true;
9743 return false;
9748 qemuDomainUpdateDeviceList(virQEMUDriverPtr driver,
9749 virDomainObjPtr vm,
9750 int asyncJob)
9752 qemuDomainObjPrivatePtr priv = vm->privateData;
9753 char **aliases;
9754 int rc;
9756 if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
9757 return -1;
9758 rc = qemuMonitorGetDeviceAliases(priv->mon, &aliases);
9759 if (qemuDomainObjExitMonitor(driver, vm) < 0)
9760 return -1;
9761 if (rc < 0)
9762 return -1;
9764 virStringListFree(priv->qemuDevices);
9765 priv->qemuDevices = aliases;
9766 return 0;
9771 qemuDomainUpdateMemoryDeviceInfo(virQEMUDriverPtr driver,
9772 virDomainObjPtr vm,
9773 int asyncJob)
9775 qemuDomainObjPrivatePtr priv = vm->privateData;
9776 virHashTablePtr meminfo = NULL;
9777 int rc;
9778 size_t i;
9780 if (vm->def->nmems == 0)
9781 return 0;
9783 if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
9784 return -1;
9786 rc = qemuMonitorGetMemoryDeviceInfo(priv->mon, &meminfo);
9788 if (qemuDomainObjExitMonitor(driver, vm) < 0) {
9789 virHashFree(meminfo);
9790 return -1;
9793 /* if qemu doesn't support the info request, just carry on */
9794 if (rc == -2)
9795 return 0;
9797 if (rc < 0)
9798 return -1;
9800 for (i = 0; i < vm->def->nmems; i++) {
9801 virDomainMemoryDefPtr mem = vm->def->mems[i];
9802 qemuMonitorMemoryDeviceInfoPtr dimm;
9804 if (!mem->info.alias)
9805 continue;
9807 if (!(dimm = virHashLookup(meminfo, mem->info.alias)))
9808 continue;
9810 mem->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM;
9811 mem->info.addr.dimm.slot = dimm->slot;
9812 mem->info.addr.dimm.base = dimm->address;
9815 virHashFree(meminfo);
9816 return 0;
9820 static bool
9821 qemuDomainABIStabilityCheck(const virDomainDef *src,
9822 const virDomainDef *dst)
9824 size_t i;
9826 if (src->mem.source != dst->mem.source) {
9827 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9828 _("Target memoryBacking source '%s' doesn't "
9829 "match source memoryBacking source'%s'"),
9830 virDomainMemorySourceTypeToString(dst->mem.source),
9831 virDomainMemorySourceTypeToString(src->mem.source));
9832 return false;
9835 for (i = 0; i < src->nmems; i++) {
9836 const char *srcAlias = src->mems[i]->info.alias;
9837 const char *dstAlias = dst->mems[i]->info.alias;
9839 if (STRNEQ_NULLABLE(srcAlias, dstAlias)) {
9840 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9841 _("Target memory device alias '%s' doesn't "
9842 "match source alias '%s'"),
9843 NULLSTR(srcAlias), NULLSTR(dstAlias));
9844 return false;
9848 return true;
9852 virDomainABIStability virQEMUDriverDomainABIStability = {
9853 .domain = qemuDomainABIStabilityCheck,
9857 static bool
9858 qemuDomainMigratableDefCheckABIStability(virQEMUDriverPtr driver,
9859 virDomainDefPtr src,
9860 virDomainDefPtr migratableSrc,
9861 virDomainDefPtr dst,
9862 virDomainDefPtr migratableDst)
9864 if (!virDomainDefCheckABIStabilityFlags(migratableSrc,
9865 migratableDst,
9866 driver->xmlopt,
9867 VIR_DOMAIN_DEF_ABI_CHECK_SKIP_VOLATILE))
9868 return false;
9870 /* Force update any skipped values from the volatile flag */
9871 dst->mem.cur_balloon = src->mem.cur_balloon;
9873 return true;
9877 #define COPY_FLAGS (VIR_DOMAIN_XML_SECURE | \
9878 VIR_DOMAIN_XML_MIGRATABLE)
9880 bool
9881 qemuDomainDefCheckABIStability(virQEMUDriverPtr driver,
9882 virDomainDefPtr src,
9883 virDomainDefPtr dst)
9885 virDomainDefPtr migratableDefSrc = NULL;
9886 virDomainDefPtr migratableDefDst = NULL;
9887 bool ret = false;
9889 if (!(migratableDefSrc = qemuDomainDefCopy(driver, src, COPY_FLAGS)) ||
9890 !(migratableDefDst = qemuDomainDefCopy(driver, dst, COPY_FLAGS)))
9891 goto cleanup;
9893 ret = qemuDomainMigratableDefCheckABIStability(driver,
9894 src, migratableDefSrc,
9895 dst, migratableDefDst);
9897 cleanup:
9898 virDomainDefFree(migratableDefSrc);
9899 virDomainDefFree(migratableDefDst);
9900 return ret;
9904 bool
9905 qemuDomainCheckABIStability(virQEMUDriverPtr driver,
9906 virDomainObjPtr vm,
9907 virDomainDefPtr dst)
9909 virDomainDefPtr migratableSrc = NULL;
9910 virDomainDefPtr migratableDst = NULL;
9911 char *xml = NULL;
9912 bool ret = false;
9914 if (!(xml = qemuDomainFormatXML(driver, vm, COPY_FLAGS)) ||
9915 !(migratableSrc = qemuDomainDefFromXML(driver, xml)) ||
9916 !(migratableDst = qemuDomainDefCopy(driver, dst, COPY_FLAGS)))
9917 goto cleanup;
9919 ret = qemuDomainMigratableDefCheckABIStability(driver,
9920 vm->def, migratableSrc,
9921 dst, migratableDst);
9923 cleanup:
9924 VIR_FREE(xml);
9925 virDomainDefFree(migratableSrc);
9926 virDomainDefFree(migratableDst);
9927 return ret;
9930 #undef COPY_FLAGS
9933 bool
9934 qemuDomainAgentAvailable(virDomainObjPtr vm,
9935 bool reportError)
9937 qemuDomainObjPrivatePtr priv = vm->privateData;
9939 if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_RUNNING) {
9940 if (reportError) {
9941 virReportError(VIR_ERR_OPERATION_INVALID, "%s",
9942 _("domain is not running"));
9944 return false;
9946 if (priv->agentError) {
9947 if (reportError) {
9948 virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
9949 _("QEMU guest agent is not "
9950 "available due to an error"));
9952 return false;
9954 if (!priv->agent) {
9955 if (qemuFindAgentConfig(vm->def)) {
9956 if (reportError) {
9957 virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
9958 _("QEMU guest agent is not connected"));
9960 return false;
9961 } else {
9962 if (reportError) {
9963 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
9964 _("QEMU guest agent is not configured"));
9966 return false;
9969 return true;
9973 static unsigned long long
9974 qemuDomainGetMemorySizeAlignment(virDomainDefPtr def)
9976 /* PPC requires the memory sizes to be rounded to 256MiB increments, so
9977 * round them to the size always. */
9978 if (ARCH_IS_PPC64(def->os.arch))
9979 return 256 * 1024;
9981 /* Align memory size. QEMU requires rounding to next 4KiB block.
9982 * We'll take the "traditional" path and round it to 1MiB*/
9984 return 1024;
9988 static unsigned long long
9989 qemuDomainGetMemoryModuleSizeAlignment(const virDomainDef *def,
9990 const virDomainMemoryDef *mem ATTRIBUTE_UNUSED)
9992 /* PPC requires the memory sizes to be rounded to 256MiB increments, so
9993 * round them to the size always. */
9994 if (ARCH_IS_PPC64(def->os.arch))
9995 return 256 * 1024;
9997 /* dimm memory modules require 2MiB alignment rather than the 1MiB we are
9998 * using elsewhere. */
9999 return 2048;
10004 qemuDomainAlignMemorySizes(virDomainDefPtr def)
10006 unsigned long long maxmemkb = virMemoryMaxValue(false) >> 10;
10007 unsigned long long maxmemcapped = virMemoryMaxValue(true) >> 10;
10008 unsigned long long initialmem = 0;
10009 unsigned long long hotplugmem = 0;
10010 unsigned long long mem;
10011 unsigned long long align = qemuDomainGetMemorySizeAlignment(def);
10012 size_t ncells = virDomainNumaGetNodeCount(def->numa);
10013 size_t i;
10015 /* align NUMA cell sizes if relevant */
10016 for (i = 0; i < ncells; i++) {
10017 mem = VIR_ROUND_UP(virDomainNumaGetNodeMemorySize(def->numa, i), align);
10018 initialmem += mem;
10020 if (mem > maxmemkb) {
10021 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10022 _("memory size of NUMA node '%zu' overflowed after "
10023 "alignment"), i);
10024 return -1;
10026 virDomainNumaSetNodeMemorySize(def->numa, i, mem);
10029 /* align initial memory size, if NUMA is present calculate it as total of
10030 * individual aligned NUMA node sizes */
10031 if (initialmem == 0)
10032 initialmem = VIR_ROUND_UP(virDomainDefGetMemoryInitial(def), align);
10034 if (initialmem > maxmemcapped) {
10035 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10036 _("initial memory size overflowed after alignment"));
10037 return -1;
10040 def->mem.max_memory = VIR_ROUND_UP(def->mem.max_memory, align);
10041 if (def->mem.max_memory > maxmemkb) {
10042 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10043 _("maximum memory size overflowed after alignment"));
10044 return -1;
10047 /* Align memory module sizes */
10048 for (i = 0; i < def->nmems; i++) {
10049 align = qemuDomainGetMemoryModuleSizeAlignment(def, def->mems[i]);
10050 def->mems[i]->size = VIR_ROUND_UP(def->mems[i]->size, align);
10051 hotplugmem += def->mems[i]->size;
10053 if (def->mems[i]->size > maxmemkb) {
10054 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10055 _("size of memory module '%zu' overflowed after "
10056 "alignment"), i);
10057 return -1;
10061 virDomainDefSetMemoryTotal(def, initialmem + hotplugmem);
10063 return 0;
10068 * qemuDomainMemoryDeviceAlignSize:
10069 * @mem: memory device definition object
10071 * Aligns the size of the memory module as qemu enforces it. The size is updated
10072 * inplace. Default rounding is now to 1 MiB (qemu requires rouding to page,
10073 * size so this should be safe).
10075 void
10076 qemuDomainMemoryDeviceAlignSize(virDomainDefPtr def,
10077 virDomainMemoryDefPtr mem)
10079 mem->size = VIR_ROUND_UP(mem->size, qemuDomainGetMemorySizeAlignment(def));
10084 * qemuDomainGetMonitor:
10085 * @vm: domain object
10087 * Returns the monitor pointer corresponding to the domain object @vm.
10089 qemuMonitorPtr
10090 qemuDomainGetMonitor(virDomainObjPtr vm)
10092 return ((qemuDomainObjPrivatePtr) vm->privateData)->mon;
10097 * qemuDomainSupportsBlockJobs:
10098 * @vm: domain object
10100 * Returns -1 in case when qemu does not support block jobs at all. Otherwise
10101 * returns 0.
10104 qemuDomainSupportsBlockJobs(virDomainObjPtr vm)
10106 qemuDomainObjPrivatePtr priv = vm->privateData;
10107 bool asynchronous = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_ASYNC);
10109 if (!asynchronous) {
10110 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10111 _("block jobs not supported with this QEMU binary"));
10112 return -1;
10115 return 0;
10120 * qemuFindAgentConfig:
10121 * @def: domain definition
10123 * Returns the pointer to the channel definition that is used to access the
10124 * guest agent if the agent is configured or NULL otherwise.
10126 virDomainChrDefPtr
10127 qemuFindAgentConfig(virDomainDefPtr def)
10129 size_t i;
10131 for (i = 0; i < def->nchannels; i++) {
10132 virDomainChrDefPtr channel = def->channels[i];
10134 if (channel->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO)
10135 continue;
10137 if (STREQ_NULLABLE(channel->target.name, "org.qemu.guest_agent.0"))
10138 return channel;
10141 return NULL;
10145 static bool
10146 qemuDomainMachineIsQ35(const char *machine,
10147 const virArch arch)
10149 if (!ARCH_IS_X86(arch))
10150 return false;
10152 if (STREQ(machine, "q35") ||
10153 STRPREFIX(machine, "pc-q35-")) {
10154 return true;
10157 return false;
10161 static bool
10162 qemuDomainMachineIsI440FX(const char *machine,
10163 const virArch arch)
10165 if (!ARCH_IS_X86(arch))
10166 return false;
10168 if (STREQ(machine, "pc") ||
10169 STRPREFIX(machine, "pc-0.") ||
10170 STRPREFIX(machine, "pc-1.") ||
10171 STRPREFIX(machine, "pc-i440fx-") ||
10172 STRPREFIX(machine, "rhel")) {
10173 return true;
10176 return false;
10180 static bool
10181 qemuDomainMachineIsS390CCW(const char *machine,
10182 const virArch arch)
10184 if (!ARCH_IS_S390(arch))
10185 return false;
10187 if (STRPREFIX(machine, "s390-ccw"))
10188 return true;
10190 return false;
10194 /* You should normally avoid this function and use
10195 * qemuDomainIsARMVirt() instead. */
10196 bool
10197 qemuDomainMachineIsARMVirt(const char *machine,
10198 const virArch arch)
10200 if (arch != VIR_ARCH_ARMV6L &&
10201 arch != VIR_ARCH_ARMV7L &&
10202 arch != VIR_ARCH_AARCH64) {
10203 return false;
10206 if (STREQ(machine, "virt") ||
10207 STRPREFIX(machine, "virt-")) {
10208 return true;
10211 return false;
10215 static bool
10216 qemuDomainMachineIsRISCVVirt(const char *machine,
10217 const virArch arch)
10219 if (!ARCH_IS_RISCV(arch))
10220 return false;
10222 if (STREQ(machine, "virt") ||
10223 STRPREFIX(machine, "virt-")) {
10224 return true;
10227 return false;
10231 /* You should normally avoid this function and use
10232 * qemuDomainIsPSeries() instead. */
10233 bool
10234 qemuDomainMachineIsPSeries(const char *machine,
10235 const virArch arch)
10237 if (!ARCH_IS_PPC64(arch))
10238 return false;
10240 if (STREQ(machine, "pseries") ||
10241 STRPREFIX(machine, "pseries-")) {
10242 return true;
10245 return false;
10249 /* You should normally avoid this function and use
10250 * qemuDomainHasBuiltinIDE() instead. */
10251 bool
10252 qemuDomainMachineHasBuiltinIDE(const char *machine,
10253 const virArch arch)
10255 return qemuDomainMachineIsI440FX(machine, arch) ||
10256 STREQ(machine, "malta") ||
10257 STREQ(machine, "sun4u") ||
10258 STREQ(machine, "g3beige");
10262 static bool
10263 qemuDomainMachineNeedsFDC(const char *machine,
10264 const virArch arch)
10266 const char *p = STRSKIP(machine, "pc-q35-");
10268 if (!ARCH_IS_X86(arch))
10269 return false;
10271 if (!p)
10272 return false;
10274 if (STRPREFIX(p, "1.") ||
10275 STREQ(p, "2.0") ||
10276 STREQ(p, "2.1") ||
10277 STREQ(p, "2.2") ||
10278 STREQ(p, "2.3")) {
10279 return false;
10282 return true;
10286 bool
10287 qemuDomainIsQ35(const virDomainDef *def)
10289 return qemuDomainMachineIsQ35(def->os.machine, def->os.arch);
10293 bool
10294 qemuDomainIsI440FX(const virDomainDef *def)
10296 return qemuDomainMachineIsI440FX(def->os.machine, def->os.arch);
10300 bool
10301 qemuDomainIsS390CCW(const virDomainDef *def)
10303 return qemuDomainMachineIsS390CCW(def->os.machine, def->os.arch);
10307 bool
10308 qemuDomainIsARMVirt(const virDomainDef *def)
10310 return qemuDomainMachineIsARMVirt(def->os.machine, def->os.arch);
10314 bool
10315 qemuDomainIsRISCVVirt(const virDomainDef *def)
10317 return qemuDomainMachineIsRISCVVirt(def->os.machine, def->os.arch);
10321 bool
10322 qemuDomainIsPSeries(const virDomainDef *def)
10324 return qemuDomainMachineIsPSeries(def->os.machine, def->os.arch);
10328 bool
10329 qemuDomainHasPCIRoot(const virDomainDef *def)
10331 int root = virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0);
10333 if (root < 0)
10334 return false;
10336 if (def->controllers[root]->model != VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT)
10337 return false;
10339 return true;
10343 bool
10344 qemuDomainHasPCIeRoot(const virDomainDef *def)
10346 int root = virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0);
10348 if (root < 0)
10349 return false;
10351 if (def->controllers[root]->model != VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)
10352 return false;
10354 return true;
10358 bool
10359 qemuDomainHasBuiltinIDE(const virDomainDef *def)
10361 return qemuDomainMachineHasBuiltinIDE(def->os.machine, def->os.arch);
10365 bool
10366 qemuDomainNeedsFDC(const virDomainDef *def)
10368 return qemuDomainMachineNeedsFDC(def->os.machine, def->os.arch);
10372 bool
10373 qemuDomainSupportsPCI(virDomainDefPtr def,
10374 virQEMUCapsPtr qemuCaps)
10376 if (def->os.arch != VIR_ARCH_ARMV6L &&
10377 def->os.arch != VIR_ARCH_ARMV7L &&
10378 def->os.arch != VIR_ARCH_AARCH64 &&
10379 !ARCH_IS_RISCV(def->os.arch)) {
10380 return true;
10383 if (STREQ(def->os.machine, "versatilepb"))
10384 return true;
10386 if ((qemuDomainIsARMVirt(def) ||
10387 qemuDomainIsRISCVVirt(def)) &&
10388 virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_GPEX)) {
10389 return true;
10392 return false;
10396 static bool
10397 qemuCheckMemoryDimmConflict(const virDomainDef *def,
10398 const virDomainMemoryDef *mem)
10400 size_t i;
10402 for (i = 0; i < def->nmems; i++) {
10403 virDomainMemoryDefPtr tmp = def->mems[i];
10405 if (tmp == mem ||
10406 tmp->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM)
10407 continue;
10409 if (mem->info.addr.dimm.slot == tmp->info.addr.dimm.slot) {
10410 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10411 _("memory device slot '%u' is already being "
10412 "used by another memory device"),
10413 mem->info.addr.dimm.slot);
10414 return true;
10417 if (mem->info.addr.dimm.base != 0 &&
10418 mem->info.addr.dimm.base == tmp->info.addr.dimm.base) {
10419 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10420 _("memory device base '0x%llx' is already being "
10421 "used by another memory device"),
10422 mem->info.addr.dimm.base);
10423 return true;
10427 return false;
10429 static int
10430 qemuDomainDefValidateMemoryHotplugDevice(const virDomainMemoryDef *mem,
10431 const virDomainDef *def)
10433 switch ((virDomainMemoryModel) mem->model) {
10434 case VIR_DOMAIN_MEMORY_MODEL_DIMM:
10435 case VIR_DOMAIN_MEMORY_MODEL_NVDIMM:
10436 if (mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM &&
10437 mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
10438 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10439 _("only 'dimm' addresses are supported for the "
10440 "pc-dimm device"));
10441 return -1;
10444 if (virDomainNumaGetNodeCount(def->numa) != 0) {
10445 if (mem->targetNode == -1) {
10446 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10447 _("target NUMA node needs to be specified for "
10448 "memory device"));
10449 return -1;
10453 if (mem->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM) {
10454 if (mem->info.addr.dimm.slot >= def->mem.memory_slots) {
10455 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10456 _("memory device slot '%u' exceeds slots "
10457 "count '%u'"),
10458 mem->info.addr.dimm.slot, def->mem.memory_slots);
10459 return -1;
10463 if (qemuCheckMemoryDimmConflict(def, mem))
10464 return -1;
10466 break;
10468 case VIR_DOMAIN_MEMORY_MODEL_NONE:
10469 case VIR_DOMAIN_MEMORY_MODEL_LAST:
10470 return -1;
10473 return 0;
10478 * qemuDomainDefValidateMemoryHotplug:
10479 * @def: domain definition
10480 * @qemuCaps: qemu capabilities object
10481 * @mem: definition of memory device that is to be added to @def with hotplug,
10482 * NULL in case of regular VM startup
10484 * Validates that the domain definition and memory modules have valid
10485 * configuration and are possibly able to accept @mem via hotplug if it's
10486 * non-NULL.
10488 * Returns 0 on success; -1 and a libvirt error on error.
10491 qemuDomainDefValidateMemoryHotplug(const virDomainDef *def,
10492 virQEMUCapsPtr qemuCaps,
10493 const virDomainMemoryDef *mem)
10495 unsigned int nmems = def->nmems;
10496 unsigned long long hotplugSpace;
10497 unsigned long long hotplugMemory = 0;
10498 bool needPCDimmCap = false;
10499 bool needNvdimmCap = false;
10500 size_t i;
10502 hotplugSpace = def->mem.max_memory - virDomainDefGetMemoryInitial(def);
10504 if (mem) {
10505 nmems++;
10506 hotplugMemory = mem->size;
10508 if (qemuDomainDefValidateMemoryHotplugDevice(mem, def) < 0)
10509 return -1;
10512 if (!virDomainDefHasMemoryHotplug(def)) {
10513 if (nmems) {
10514 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10515 _("cannot use/hotplug a memory device when domain "
10516 "'maxMemory' is not defined"));
10517 return -1;
10520 return 0;
10523 if (!ARCH_IS_PPC64(def->os.arch)) {
10524 /* due to guest support, qemu would silently enable NUMA with one node
10525 * once the memory hotplug backend is enabled. To avoid possible
10526 * confusion we will enforce user originated numa configuration along
10527 * with memory hotplug. */
10528 if (virDomainNumaGetNodeCount(def->numa) == 0) {
10529 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10530 _("At least one numa node has to be configured when "
10531 "enabling memory hotplug"));
10532 return -1;
10536 if (nmems > def->mem.memory_slots) {
10537 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10538 _("memory device count '%u' exceeds slots count '%u'"),
10539 nmems, def->mem.memory_slots);
10540 return -1;
10543 for (i = 0; i < def->nmems; i++) {
10544 hotplugMemory += def->mems[i]->size;
10546 switch ((virDomainMemoryModel) def->mems[i]->model) {
10547 case VIR_DOMAIN_MEMORY_MODEL_DIMM:
10548 needPCDimmCap = true;
10549 break;
10551 case VIR_DOMAIN_MEMORY_MODEL_NVDIMM:
10552 needNvdimmCap = true;
10553 break;
10555 case VIR_DOMAIN_MEMORY_MODEL_NONE:
10556 case VIR_DOMAIN_MEMORY_MODEL_LAST:
10557 break;
10560 /* already existing devices don't need to be checked on hotplug */
10561 if (!mem &&
10562 qemuDomainDefValidateMemoryHotplugDevice(def->mems[i], def) < 0)
10563 return -1;
10566 if (needPCDimmCap &&
10567 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PC_DIMM)) {
10568 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10569 _("memory hotplug isn't supported by this QEMU binary"));
10570 return -1;
10573 if (needNvdimmCap &&
10574 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_NVDIMM)) {
10575 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10576 _("nvdimm isn't supported by this QEMU binary"));
10577 return -1;
10580 if (hotplugMemory > hotplugSpace) {
10581 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10582 _("memory device total size exceeds hotplug space"));
10583 return -1;
10586 return 0;
10591 * qemuDomainUpdateCurrentMemorySize:
10593 * In case when the balloon is not present for the domain, the function
10594 * recalculates the maximum size to reflect possible changes.
10596 void
10597 qemuDomainUpdateCurrentMemorySize(virDomainObjPtr vm)
10599 /* inactive domain doesn't need size update */
10600 if (!virDomainObjIsActive(vm))
10601 return;
10603 /* if no balloning is available, the current size equals to the current
10604 * full memory size */
10605 if (!virDomainDefHasMemballoon(vm->def))
10606 vm->def->mem.cur_balloon = virDomainDefGetMemoryTotal(vm->def);
10611 * getPPC64MemLockLimitBytes:
10612 * @def: domain definition
10614 * A PPC64 helper that calculates the memory locking limit in order for
10615 * the guest to operate properly.
10617 static unsigned long long
10618 getPPC64MemLockLimitBytes(virDomainDefPtr def)
10620 unsigned long long memKB = 0;
10621 unsigned long long baseLimit = 0;
10622 unsigned long long memory = 0;
10623 unsigned long long maxMemory = 0;
10624 unsigned long long passthroughLimit = 0;
10625 size_t i, nPCIHostBridges = 0;
10626 bool usesVFIO = false;
10628 for (i = 0; i < def->ncontrollers; i++) {
10629 virDomainControllerDefPtr cont = def->controllers[i];
10631 if (!virDomainControllerIsPSeriesPHB(cont))
10632 continue;
10634 nPCIHostBridges++;
10637 for (i = 0; i < def->nhostdevs; i++) {
10638 virDomainHostdevDefPtr dev = def->hostdevs[i];
10640 if (dev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
10641 dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
10642 dev->source.subsys.u.pci.backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
10643 usesVFIO = true;
10644 break;
10648 memory = virDomainDefGetMemoryTotal(def);
10650 if (def->mem.max_memory)
10651 maxMemory = def->mem.max_memory;
10652 else
10653 maxMemory = memory;
10655 /* baseLimit := maxMemory / 128 (a)
10656 * + 4 MiB * #PHBs + 8 MiB (b)
10658 * (a) is the hash table
10660 * (b) is accounting for the 32-bit DMA window - it could be either the
10661 * KVM accelerated TCE tables for emulated devices, or the VFIO
10662 * userspace view. The 4 MiB per-PHB (including the default one) covers
10663 * a 2GiB DMA window: default is 1GiB, but it's possible it'll be
10664 * increased to help performance. The 8 MiB extra should be plenty for
10665 * the TCE table index for any reasonable number of PHBs and several
10666 * spapr-vlan or spapr-vscsi devices (512kB + a tiny bit each) */
10667 baseLimit = maxMemory / 128 +
10668 4096 * nPCIHostBridges +
10669 8192;
10671 /* passthroughLimit := max( 2 GiB * #PHBs, (c)
10672 * memory (d)
10673 * + memory * 1/512 * #PHBs + 8 MiB ) (e)
10675 * (c) is the pre-DDW VFIO DMA window accounting. We're allowing 2 GiB
10676 * rather than 1 GiB
10678 * (d) is the with-DDW (and memory pre-registration and related
10679 * features) DMA window accounting - assuming that we only account RAM
10680 * once, even if mapped to multiple PHBs
10682 * (e) is the with-DDW userspace view and overhead for the 64-bit DMA
10683 * window. This is based a bit on expected guest behaviour, but there
10684 * really isn't a way to completely avoid that. We assume the guest
10685 * requests a 64-bit DMA window (per PHB) just big enough to map all
10686 * its RAM. 4 kiB page size gives the 1/512; it will be less with 64
10687 * kiB pages, less still if the guest is mapped with hugepages (unlike
10688 * the default 32-bit DMA window, DDW windows can use large IOMMU
10689 * pages). 8 MiB is for second and further level overheads, like (b) */
10690 if (usesVFIO)
10691 passthroughLimit = MAX(2 * 1024 * 1024 * nPCIHostBridges,
10692 memory +
10693 memory / 512 * nPCIHostBridges + 8192);
10695 memKB = baseLimit + passthroughLimit;
10697 return memKB << 10;
10702 * qemuDomainGetMemLockLimitBytes:
10703 * @def: domain definition
10705 * Calculate the memory locking limit that needs to be set in order for
10706 * the guest to operate properly. The limit depends on a number of factors,
10707 * including certain configuration options and less immediately apparent ones
10708 * such as the guest architecture or the use of certain devices.
10710 * Returns: the memory locking limit, or 0 if setting the limit is not needed
10712 unsigned long long
10713 qemuDomainGetMemLockLimitBytes(virDomainDefPtr def)
10715 unsigned long long memKB = 0;
10716 size_t i;
10718 /* prefer the hard limit */
10719 if (virMemoryLimitIsSet(def->mem.hard_limit)) {
10720 memKB = def->mem.hard_limit;
10721 goto done;
10724 /* If the guest wants its memory to be locked, we need to raise the memory
10725 * locking limit so that the OS will not refuse allocation requests;
10726 * however, there is no reliable way for us to figure out how much memory
10727 * the QEMU process will allocate for its own use, so our only way out is
10728 * to remove the limit altogether. Use with extreme care */
10729 if (def->mem.locked)
10730 return VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
10732 if (ARCH_IS_PPC64(def->os.arch) && def->virtType == VIR_DOMAIN_VIRT_KVM)
10733 return getPPC64MemLockLimitBytes(def);
10735 /* For device passthrough using VFIO the guest memory and MMIO memory
10736 * regions need to be locked persistent in order to allow DMA.
10738 * Currently the below limit is based on assumptions about the x86 platform.
10740 * The chosen value of 1GiB below originates from x86 systems where it was
10741 * used as space reserved for the MMIO region for the whole system.
10743 * On x86_64 systems the MMIO regions of the IOMMU mapped devices don't
10744 * count towards the locked memory limit since the memory is owned by the
10745 * device. Emulated devices though do count, but the regions are usually
10746 * small. Although it's not guaranteed that the limit will be enough for all
10747 * configurations it didn't pose a problem for now.
10749 * http://www.redhat.com/archives/libvir-list/2015-November/msg00329.html
10751 * Note that this may not be valid for all platforms.
10753 for (i = 0; i < def->nhostdevs; i++) {
10754 virDomainHostdevSubsysPtr subsys = &def->hostdevs[i]->source.subsys;
10756 if (def->hostdevs[i]->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
10757 (subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV ||
10758 (subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
10759 subsys->u.pci.backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO))) {
10760 memKB = virDomainDefGetMemoryTotal(def) + 1024 * 1024;
10761 goto done;
10765 done:
10766 return memKB << 10;
10771 * qemuDomainAdjustMaxMemLock:
10772 * @vm: domain
10774 * Adjust the memory locking limit for the QEMU process associated to @vm, in
10775 * order to comply with VFIO or architecture requirements.
10777 * The limit will not be changed unless doing so is needed; the first time
10778 * the limit is changed, the original (default) limit is stored in @vm and
10779 * that value will be restored if qemuDomainAdjustMaxMemLock() is called once
10780 * memory locking is no longer required.
10782 * Returns: 0 on success, <0 on failure
10785 qemuDomainAdjustMaxMemLock(virDomainObjPtr vm)
10787 unsigned long long bytes = 0;
10788 int ret = -1;
10790 bytes = qemuDomainGetMemLockLimitBytes(vm->def);
10792 if (bytes) {
10793 /* If this is the first time adjusting the limit, save the current
10794 * value so that we can restore it once memory locking is no longer
10795 * required. Failing to obtain the current limit is not a critical
10796 * failure, it just means we'll be unable to lower it later */
10797 if (!vm->original_memlock) {
10798 if (virProcessGetMaxMemLock(vm->pid, &(vm->original_memlock)) < 0)
10799 vm->original_memlock = 0;
10801 } else {
10802 /* Once memory locking is no longer required, we can restore the
10803 * original, usually very low, limit */
10804 bytes = vm->original_memlock;
10805 vm->original_memlock = 0;
10808 /* Trying to set the memory locking limit to zero is a no-op */
10809 if (virProcessSetMaxMemLock(vm->pid, bytes) < 0)
10810 goto out;
10812 ret = 0;
10814 out:
10815 return ret;
10819 * qemuDomainHasVcpuPids:
10820 * @vm: Domain object
10822 * Returns true if we were able to successfully detect vCPU pids for the VM.
10824 bool
10825 qemuDomainHasVcpuPids(virDomainObjPtr vm)
10827 size_t i;
10828 size_t maxvcpus = virDomainDefGetVcpusMax(vm->def);
10829 virDomainVcpuDefPtr vcpu;
10831 for (i = 0; i < maxvcpus; i++) {
10832 vcpu = virDomainDefGetVcpu(vm->def, i);
10834 if (QEMU_DOMAIN_VCPU_PRIVATE(vcpu)->tid > 0)
10835 return true;
10838 return false;
10843 * qemuDomainGetVcpuPid:
10844 * @vm: domain object
10845 * @vcpu: cpu id
10847 * Returns the vCPU pid. If @vcpu is offline or out of range 0 is returned.
10849 pid_t
10850 qemuDomainGetVcpuPid(virDomainObjPtr vm,
10851 unsigned int vcpuid)
10853 virDomainVcpuDefPtr vcpu = virDomainDefGetVcpu(vm->def, vcpuid);
10854 return QEMU_DOMAIN_VCPU_PRIVATE(vcpu)->tid;
10859 * qemuDomainValidateVcpuInfo:
10861 * Validates vcpu thread information. If vcpu thread IDs are reported by qemu,
10862 * this function validates that online vcpus have thread info present and
10863 * offline vcpus don't.
10865 * Returns 0 on success -1 on error.
10868 qemuDomainValidateVcpuInfo(virDomainObjPtr vm)
10870 size_t maxvcpus = virDomainDefGetVcpusMax(vm->def);
10871 virDomainVcpuDefPtr vcpu;
10872 qemuDomainVcpuPrivatePtr vcpupriv;
10873 size_t i;
10875 if (!qemuDomainHasVcpuPids(vm))
10876 return 0;
10878 for (i = 0; i < maxvcpus; i++) {
10879 vcpu = virDomainDefGetVcpu(vm->def, i);
10880 vcpupriv = QEMU_DOMAIN_VCPU_PRIVATE(vcpu);
10882 if (vcpu->online && vcpupriv->tid == 0) {
10883 virReportError(VIR_ERR_INTERNAL_ERROR,
10884 _("qemu didn't report thread id for vcpu '%zu'"), i);
10885 return -1;
10888 if (!vcpu->online && vcpupriv->tid != 0) {
10889 virReportError(VIR_ERR_INTERNAL_ERROR,
10890 _("qemu reported thread id for inactive vcpu '%zu'"),
10892 return -1;
10896 return 0;
10900 bool
10901 qemuDomainSupportsNewVcpuHotplug(virDomainObjPtr vm)
10903 qemuDomainObjPrivatePtr priv = vm->privateData;
10905 return virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_QUERY_HOTPLUGGABLE_CPUS);
10910 * qemuDomainRefreshVcpuInfo:
10911 * @driver: qemu driver data
10912 * @vm: domain object
10913 * @asyncJob: current asynchronous job type
10914 * @state: refresh vcpu state
10916 * Updates vCPU information private data of @vm. Due to historical reasons this
10917 * function returns success even if some data were not reported by qemu.
10919 * If @state is true, the vcpu state is refreshed as reported by the monitor.
10921 * Returns 0 on success and -1 on fatal error.
10924 qemuDomainRefreshVcpuInfo(virQEMUDriverPtr driver,
10925 virDomainObjPtr vm,
10926 int asyncJob,
10927 bool state)
10929 virDomainVcpuDefPtr vcpu;
10930 qemuDomainVcpuPrivatePtr vcpupriv;
10931 qemuMonitorCPUInfoPtr info = NULL;
10932 size_t maxvcpus = virDomainDefGetVcpusMax(vm->def);
10933 size_t i, j;
10934 bool hotplug;
10935 bool fast;
10936 bool validTIDs = true;
10937 int rc;
10938 int ret = -1;
10940 hotplug = qemuDomainSupportsNewVcpuHotplug(vm);
10941 fast = virQEMUCapsGet(QEMU_DOMAIN_PRIVATE(vm)->qemuCaps,
10942 QEMU_CAPS_QUERY_CPUS_FAST);
10944 VIR_DEBUG("Maxvcpus %zu hotplug %d fast query %d", maxvcpus, hotplug, fast);
10946 if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
10947 return -1;
10949 rc = qemuMonitorGetCPUInfo(qemuDomainGetMonitor(vm), &info, maxvcpus,
10950 hotplug, fast);
10952 if (qemuDomainObjExitMonitor(driver, vm) < 0)
10953 goto cleanup;
10955 if (rc < 0)
10956 goto cleanup;
10959 * The query-cpus[-fast] commands return information
10960 * about the vCPUs, including the OS level PID that
10961 * is executing the vCPU.
10963 * For KVM there is always a 1-1 mapping between
10964 * vCPUs and host OS PIDs.
10966 * For TCG things are a little more complicated.
10968 * - In some cases the vCPUs will all have the same
10969 * PID as the main emulator thread.
10970 * - In some cases the first vCPU will have a distinct
10971 * PID, but other vCPUs will share the emulator thread
10973 * For MTTCG, things work the same as KVM, with each
10974 * vCPU getting its own PID.
10976 * We use the Host OS PIDs for doing vCPU pinning
10977 * and reporting. The TCG data reporting will result
10978 * in bad behaviour such as pinning the wrong PID.
10979 * We must thus detect and discard bogus PID info
10980 * from TCG, while still honouring the modern MTTCG
10981 * impl which we can support.
10983 for (i = 0; i < maxvcpus && validTIDs; i++) {
10984 if (info[i].tid == vm->pid) {
10985 VIR_DEBUG("vCPU[%zu] PID %llu duplicates process",
10986 i, (unsigned long long)info[i].tid);
10987 validTIDs = false;
10990 for (j = 0; j < i; j++) {
10991 if (info[i].tid != 0 && info[i].tid == info[j].tid) {
10992 VIR_DEBUG("vCPU[%zu] PID %llu duplicates vCPU[%zu]",
10993 i, (unsigned long long)info[i].tid, j);
10994 validTIDs = false;
10998 if (validTIDs)
10999 VIR_DEBUG("vCPU[%zu] PID %llu is valid",
11000 i, (unsigned long long)info[i].tid);
11003 VIR_DEBUG("Extracting vCPU information validTIDs=%d", validTIDs);
11004 for (i = 0; i < maxvcpus; i++) {
11005 vcpu = virDomainDefGetVcpu(vm->def, i);
11006 vcpupriv = QEMU_DOMAIN_VCPU_PRIVATE(vcpu);
11008 if (validTIDs)
11009 vcpupriv->tid = info[i].tid;
11011 vcpupriv->socket_id = info[i].socket_id;
11012 vcpupriv->core_id = info[i].core_id;
11013 vcpupriv->thread_id = info[i].thread_id;
11014 vcpupriv->node_id = info[i].node_id;
11015 vcpupriv->vcpus = info[i].vcpus;
11016 VIR_FREE(vcpupriv->type);
11017 VIR_STEAL_PTR(vcpupriv->type, info[i].type);
11018 VIR_FREE(vcpupriv->alias);
11019 VIR_STEAL_PTR(vcpupriv->alias, info[i].alias);
11020 vcpupriv->enable_id = info[i].id;
11021 vcpupriv->qemu_id = info[i].qemu_id;
11023 if (hotplug && state) {
11024 vcpu->online = info[i].online;
11025 if (info[i].hotpluggable)
11026 vcpu->hotpluggable = VIR_TRISTATE_BOOL_YES;
11027 else
11028 vcpu->hotpluggable = VIR_TRISTATE_BOOL_NO;
11032 ret = 0;
11034 cleanup:
11035 qemuMonitorCPUInfoFree(info, maxvcpus);
11036 return ret;
11040 * qemuDomainGetVcpuHalted:
11041 * @vm: domain object
11042 * @vcpu: cpu id
11044 * Returns the vCPU halted state.
11046 bool
11047 qemuDomainGetVcpuHalted(virDomainObjPtr vm,
11048 unsigned int vcpuid)
11050 virDomainVcpuDefPtr vcpu = virDomainDefGetVcpu(vm->def, vcpuid);
11051 return QEMU_DOMAIN_VCPU_PRIVATE(vcpu)->halted;
11055 * qemuDomainRefreshVcpuHalted:
11056 * @driver: qemu driver data
11057 * @vm: domain object
11058 * @asyncJob: current asynchronous job type
11060 * Updates vCPU halted state in the private data of @vm.
11062 * Returns 0 on success and -1 on error
11065 qemuDomainRefreshVcpuHalted(virQEMUDriverPtr driver,
11066 virDomainObjPtr vm,
11067 int asyncJob)
11069 virDomainVcpuDefPtr vcpu;
11070 qemuDomainVcpuPrivatePtr vcpupriv;
11071 size_t maxvcpus = virDomainDefGetVcpusMax(vm->def);
11072 virBitmapPtr haltedmap = NULL;
11073 size_t i;
11074 int ret = -1;
11075 bool fast;
11077 /* Not supported currently for TCG, see qemuDomainRefreshVcpuInfo */
11078 if (vm->def->virtType == VIR_DOMAIN_VIRT_QEMU)
11079 return 0;
11081 /* The halted state is interresting only on s390(x). On other platforms
11082 * the data would be stale at the time when it would be used.
11083 * Calling qemuMonitorGetCpuHalted() can adversely affect the running
11084 * VM's performance unless QEMU supports query-cpus-fast.
11086 if (!ARCH_IS_S390(vm->def->os.arch) ||
11087 !virQEMUCapsGet(QEMU_DOMAIN_PRIVATE(vm)->qemuCaps,
11088 QEMU_CAPS_QUERY_CPUS_FAST))
11089 return 0;
11091 if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
11092 return -1;
11094 fast = virQEMUCapsGet(QEMU_DOMAIN_PRIVATE(vm)->qemuCaps,
11095 QEMU_CAPS_QUERY_CPUS_FAST);
11096 haltedmap = qemuMonitorGetCpuHalted(qemuDomainGetMonitor(vm), maxvcpus,
11097 fast);
11098 if (qemuDomainObjExitMonitor(driver, vm) < 0 || !haltedmap)
11099 goto cleanup;
11101 for (i = 0; i < maxvcpus; i++) {
11102 vcpu = virDomainDefGetVcpu(vm->def, i);
11103 vcpupriv = QEMU_DOMAIN_VCPU_PRIVATE(vcpu);
11104 vcpupriv->halted = virTristateBoolFromBool(virBitmapIsBitSet(haltedmap,
11105 vcpupriv->qemu_id));
11108 ret = 0;
11110 cleanup:
11111 virBitmapFree(haltedmap);
11112 return ret;
11115 bool
11116 qemuDomainSupportsNicdev(virDomainDefPtr def,
11117 virDomainNetDefPtr net)
11119 /* non-virtio ARM nics require legacy -net nic */
11120 if (((def->os.arch == VIR_ARCH_ARMV6L) ||
11121 (def->os.arch == VIR_ARCH_ARMV7L) ||
11122 (def->os.arch == VIR_ARCH_AARCH64)) &&
11123 net->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
11124 net->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
11125 return false;
11127 return true;
11130 bool
11131 qemuDomainNetSupportsMTU(virDomainNetType type)
11133 switch (type) {
11134 case VIR_DOMAIN_NET_TYPE_NETWORK:
11135 case VIR_DOMAIN_NET_TYPE_BRIDGE:
11136 case VIR_DOMAIN_NET_TYPE_ETHERNET:
11137 case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
11138 return true;
11139 case VIR_DOMAIN_NET_TYPE_USER:
11140 case VIR_DOMAIN_NET_TYPE_SERVER:
11141 case VIR_DOMAIN_NET_TYPE_CLIENT:
11142 case VIR_DOMAIN_NET_TYPE_MCAST:
11143 case VIR_DOMAIN_NET_TYPE_INTERNAL:
11144 case VIR_DOMAIN_NET_TYPE_DIRECT:
11145 case VIR_DOMAIN_NET_TYPE_HOSTDEV:
11146 case VIR_DOMAIN_NET_TYPE_UDP:
11147 case VIR_DOMAIN_NET_TYPE_LAST:
11148 break;
11150 return false;
11154 virDomainDiskDefPtr
11155 qemuDomainDiskByName(virDomainDefPtr def,
11156 const char *name)
11158 virDomainDiskDefPtr ret;
11160 if (!(ret = virDomainDiskByName(def, name, true))) {
11161 virReportError(VIR_ERR_INVALID_ARG, "%s",
11162 _("No device found for specified path"));
11163 return NULL;
11166 return ret;
11171 * qemuDomainDefValidateDiskLunSource:
11172 * @src: disk source struct
11174 * Validate whether the disk source is valid for disk device='lun'.
11176 * Returns 0 if the configuration is valid -1 and a libvirt error if the soure
11177 * is invalid.
11180 qemuDomainDefValidateDiskLunSource(const virStorageSource *src)
11182 if (virStorageSourceGetActualType(src) == VIR_STORAGE_TYPE_NETWORK) {
11183 if (src->protocol != VIR_STORAGE_NET_PROTOCOL_ISCSI) {
11184 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11185 _("disk device='lun' is not supported "
11186 "for protocol='%s'"),
11187 virStorageNetProtocolTypeToString(src->protocol));
11188 return -1;
11190 } else if (!virStorageSourceIsBlockLocal(src)) {
11191 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
11192 _("disk device='lun' is only valid for block "
11193 "type disk source"));
11194 return -1;
11197 return 0;
11202 qemuDomainPrepareChannel(virDomainChrDefPtr channel,
11203 const char *domainChannelTargetDir)
11205 if (channel->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO ||
11206 channel->source->type != VIR_DOMAIN_CHR_TYPE_UNIX ||
11207 channel->source->data.nix.path)
11208 return 0;
11210 if (channel->target.name) {
11211 if (virAsprintf(&channel->source->data.nix.path,
11212 "%s/%s", domainChannelTargetDir,
11213 channel->target.name) < 0)
11214 return -1;
11215 } else {
11216 /* Generate a unique name */
11217 if (virAsprintf(&channel->source->data.nix.path,
11218 "%s/vioser-%02d-%02d-%02d.sock",
11219 domainChannelTargetDir,
11220 channel->info.addr.vioserial.controller,
11221 channel->info.addr.vioserial.bus,
11222 channel->info.addr.vioserial.port) < 0)
11223 return -1;
11226 return 0;
11230 /* qemuDomainPrepareChardevSourceTLS:
11231 * @source: pointer to host interface data for char devices
11232 * @cfg: driver configuration
11234 * Updates host interface TLS encryption setting based on qemu.conf
11235 * for char devices. This will be presented as "tls='yes|no'" in
11236 * live XML of a guest.
11238 void
11239 qemuDomainPrepareChardevSourceTLS(virDomainChrSourceDefPtr source,
11240 virQEMUDriverConfigPtr cfg)
11242 if (source->type == VIR_DOMAIN_CHR_TYPE_TCP) {
11243 if (source->data.tcp.haveTLS == VIR_TRISTATE_BOOL_ABSENT) {
11244 if (cfg->chardevTLS)
11245 source->data.tcp.haveTLS = VIR_TRISTATE_BOOL_YES;
11246 else
11247 source->data.tcp.haveTLS = VIR_TRISTATE_BOOL_NO;
11248 source->data.tcp.tlsFromConfig = true;
11254 /* qemuDomainPrepareChardevSource:
11255 * @def: live domain definition
11256 * @cfg: driver configuration
11258 * Iterate through all devices that use virDomainChrSourceDefPtr as host
11259 * interface part.
11261 void
11262 qemuDomainPrepareChardevSource(virDomainDefPtr def,
11263 virQEMUDriverConfigPtr cfg)
11265 size_t i;
11267 for (i = 0; i < def->nserials; i++)
11268 qemuDomainPrepareChardevSourceTLS(def->serials[i]->source, cfg);
11270 for (i = 0; i < def->nparallels; i++)
11271 qemuDomainPrepareChardevSourceTLS(def->parallels[i]->source, cfg);
11273 for (i = 0; i < def->nchannels; i++)
11274 qemuDomainPrepareChardevSourceTLS(def->channels[i]->source, cfg);
11276 for (i = 0; i < def->nconsoles; i++)
11277 qemuDomainPrepareChardevSourceTLS(def->consoles[i]->source, cfg);
11279 for (i = 0; i < def->nrngs; i++)
11280 if (def->rngs[i]->backend == VIR_DOMAIN_RNG_BACKEND_EGD)
11281 qemuDomainPrepareChardevSourceTLS(def->rngs[i]->source.chardev, cfg);
11283 for (i = 0; i < def->nsmartcards; i++)
11284 if (def->smartcards[i]->type == VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH)
11285 qemuDomainPrepareChardevSourceTLS(def->smartcards[i]->data.passthru,
11286 cfg);
11288 for (i = 0; i < def->nredirdevs; i++)
11289 qemuDomainPrepareChardevSourceTLS(def->redirdevs[i]->source, cfg);
11293 static int
11294 qemuProcessPrepareStorageSourceTLSVxhs(virStorageSourcePtr src,
11295 virQEMUDriverConfigPtr cfg)
11297 /* VxHS uses only client certificates and thus has no need for
11298 * the server-key.pem nor a secret that could be used to decrypt
11299 * the it, so no need to add a secinfo for a secret UUID. */
11300 if (src->haveTLS == VIR_TRISTATE_BOOL_ABSENT) {
11301 if (cfg->vxhsTLS)
11302 src->haveTLS = VIR_TRISTATE_BOOL_YES;
11303 else
11304 src->haveTLS = VIR_TRISTATE_BOOL_NO;
11305 src->tlsFromConfig = true;
11308 if (src->haveTLS == VIR_TRISTATE_BOOL_YES) {
11309 if (VIR_STRDUP(src->tlsCertdir, cfg->vxhsTLSx509certdir) < 0)
11310 return -1;
11313 return 0;
11317 static int
11318 qemuProcessPrepareStorageSourceTLSNBD(virStorageSourcePtr src,
11319 virQEMUDriverConfigPtr cfg,
11320 virQEMUCapsPtr qemuCaps)
11322 if (src->haveTLS == VIR_TRISTATE_BOOL_ABSENT) {
11323 if (cfg->nbdTLS)
11324 src->haveTLS = VIR_TRISTATE_BOOL_YES;
11325 else
11326 src->haveTLS = VIR_TRISTATE_BOOL_NO;
11327 src->tlsFromConfig = true;
11330 if (src->haveTLS == VIR_TRISTATE_BOOL_YES) {
11331 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_NBD_TLS)) {
11332 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
11333 _("this qemu does not support TLS transport for NBD"));
11334 return -1;
11337 if (VIR_STRDUP(src->tlsCertdir, cfg->nbdTLSx509certdir) < 0)
11338 return -1;
11341 return 0;
11345 /* qemuProcessPrepareStorageSourceTLS:
11346 * @source: source for a disk
11347 * @cfg: driver configuration
11348 * @parentAlias: alias of the parent device
11350 * Updates host interface TLS encryption setting based on qemu.conf
11351 * for disk devices. This will be presented as "tls='yes|no'" in
11352 * live XML of a guest.
11354 * Returns 0 on success, -1 on bad config/failure
11356 static int
11357 qemuDomainPrepareStorageSourceTLS(virStorageSourcePtr src,
11358 virQEMUDriverConfigPtr cfg,
11359 const char *parentAlias,
11360 virQEMUCapsPtr qemuCaps)
11362 if (virStorageSourceGetActualType(src) != VIR_STORAGE_TYPE_NETWORK)
11363 return 0;
11365 switch ((virStorageNetProtocol) src->protocol) {
11366 case VIR_STORAGE_NET_PROTOCOL_VXHS:
11367 if (qemuProcessPrepareStorageSourceTLSVxhs(src, cfg) < 0)
11368 return -1;
11369 break;
11371 case VIR_STORAGE_NET_PROTOCOL_NBD:
11372 if (qemuProcessPrepareStorageSourceTLSNBD(src, cfg, qemuCaps) < 0)
11373 return -1;
11374 break;
11376 case VIR_STORAGE_NET_PROTOCOL_RBD:
11377 case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
11378 case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
11379 case VIR_STORAGE_NET_PROTOCOL_ISCSI:
11380 case VIR_STORAGE_NET_PROTOCOL_HTTP:
11381 case VIR_STORAGE_NET_PROTOCOL_HTTPS:
11382 case VIR_STORAGE_NET_PROTOCOL_FTP:
11383 case VIR_STORAGE_NET_PROTOCOL_FTPS:
11384 case VIR_STORAGE_NET_PROTOCOL_TFTP:
11385 case VIR_STORAGE_NET_PROTOCOL_SSH:
11386 if (src->haveTLS == VIR_TRISTATE_BOOL_YES) {
11387 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11388 _("TLS transport is not supported for disk protocol '%s'"),
11389 virStorageNetProtocolTypeToString(src->protocol));
11390 return -1;
11392 break;
11394 case VIR_STORAGE_NET_PROTOCOL_NONE:
11395 case VIR_STORAGE_NET_PROTOCOL_LAST:
11396 default:
11397 virReportEnumRangeError(virStorageNetProtocol, src->protocol);
11398 return -1;
11401 if (src->haveTLS == VIR_TRISTATE_BOOL_YES &&
11402 !(src->tlsAlias = qemuAliasTLSObjFromSrcAlias(parentAlias)))
11403 return -1;
11405 return 0;
11410 qemuDomainPrepareShmemChardev(virDomainShmemDefPtr shmem)
11412 if (!shmem->server.enabled ||
11413 shmem->server.chr.data.nix.path)
11414 return 0;
11416 return virAsprintf(&shmem->server.chr.data.nix.path,
11417 "/var/lib/libvirt/shmem-%s-sock",
11418 shmem->name);
11423 * qemuDomainVcpuHotplugIsInOrder:
11424 * @def: domain definition
11426 * Returns true if online vcpus were added in order (clustered behind vcpu0
11427 * with increasing order).
11429 bool
11430 qemuDomainVcpuHotplugIsInOrder(virDomainDefPtr def)
11432 size_t maxvcpus = virDomainDefGetVcpusMax(def);
11433 virDomainVcpuDefPtr vcpu;
11434 unsigned int prevorder = 0;
11435 size_t seenonlinevcpus = 0;
11436 size_t i;
11438 for (i = 0; i < maxvcpus; i++) {
11439 vcpu = virDomainDefGetVcpu(def, i);
11441 if (!vcpu->online)
11442 break;
11444 if (vcpu->order < prevorder)
11445 break;
11447 if (vcpu->order > prevorder)
11448 prevorder = vcpu->order;
11450 seenonlinevcpus++;
11453 return seenonlinevcpus == virDomainDefGetVcpus(def);
11458 * qemuDomainVcpuPersistOrder:
11459 * @def: domain definition
11461 * Saves the order of vcpus detected from qemu to the domain definition.
11462 * The private data note the order only for the entry describing the
11463 * hotpluggable entity. This function copies the order into the definition part
11464 * of all sub entities.
11466 void
11467 qemuDomainVcpuPersistOrder(virDomainDefPtr def)
11469 size_t maxvcpus = virDomainDefGetVcpusMax(def);
11470 virDomainVcpuDefPtr vcpu;
11471 qemuDomainVcpuPrivatePtr vcpupriv;
11472 unsigned int prevorder = 0;
11473 size_t i;
11475 for (i = 0; i < maxvcpus; i++) {
11476 vcpu = virDomainDefGetVcpu(def, i);
11477 vcpupriv = QEMU_DOMAIN_VCPU_PRIVATE(vcpu);
11479 if (!vcpu->online) {
11480 vcpu->order = 0;
11481 } else {
11482 if (vcpupriv->enable_id != 0)
11483 prevorder = vcpupriv->enable_id;
11485 vcpu->order = prevorder;
11492 qemuDomainCheckMonitor(virQEMUDriverPtr driver,
11493 virDomainObjPtr vm,
11494 qemuDomainAsyncJob asyncJob)
11496 qemuDomainObjPrivatePtr priv = vm->privateData;
11497 int ret;
11499 if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
11500 return -1;
11502 ret = qemuMonitorCheck(priv->mon);
11504 if (qemuDomainObjExitMonitor(driver, vm) < 0)
11505 return -1;
11507 return ret;
11511 bool
11512 qemuDomainSupportsVideoVga(virDomainVideoDefPtr video,
11513 virQEMUCapsPtr qemuCaps)
11515 if (video->type == VIR_DOMAIN_VIDEO_TYPE_VIRTIO &&
11516 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_VGA))
11517 return false;
11519 return true;
11524 * qemuDomainGetHostdevPath:
11525 * @def: domain definition
11526 * @dev: host device definition
11527 * @teardown: true if device will be removed
11528 * @npaths: number of items in @path and @perms arrays
11529 * @path: resulting path to @dev
11530 * @perms: Optional pointer to VIR_CGROUP_DEVICE_* perms
11532 * For given device @dev fetch its host path and store it at
11533 * @path. If a device requires other paths to be present/allowed
11534 * they are stored in the @path array after the actual path.
11535 * Optionally, caller can get @perms on the path (e.g. rw/ro).
11537 * The caller is responsible for freeing the memory.
11539 * Returns 0 on success, -1 otherwise.
11542 qemuDomainGetHostdevPath(virDomainDefPtr def,
11543 virDomainHostdevDefPtr dev,
11544 bool teardown,
11545 size_t *npaths,
11546 char ***path,
11547 int **perms)
11549 int ret = -1;
11550 virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
11551 virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
11552 virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
11553 virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
11554 virDomainHostdevSubsysMediatedDevPtr mdevsrc = &dev->source.subsys.u.mdev;
11555 virPCIDevicePtr pci = NULL;
11556 virUSBDevicePtr usb = NULL;
11557 virSCSIDevicePtr scsi = NULL;
11558 virSCSIVHostDevicePtr host = NULL;
11559 char *tmpPath = NULL;
11560 bool freeTmpPath = false;
11561 bool includeVFIO = false;
11562 char **tmpPaths = NULL;
11563 int *tmpPerms = NULL;
11564 size_t i, tmpNpaths = 0;
11565 int perm = 0;
11567 *npaths = 0;
11569 switch ((virDomainHostdevMode) dev->mode) {
11570 case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
11571 switch ((virDomainHostdevSubsysType)dev->source.subsys.type) {
11572 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
11573 if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
11574 pci = virPCIDeviceNew(pcisrc->addr.domain,
11575 pcisrc->addr.bus,
11576 pcisrc->addr.slot,
11577 pcisrc->addr.function);
11578 if (!pci)
11579 goto cleanup;
11581 if (!(tmpPath = virPCIDeviceGetIOMMUGroupDev(pci)))
11582 goto cleanup;
11583 freeTmpPath = true;
11585 perm = VIR_CGROUP_DEVICE_RW;
11586 if (teardown) {
11587 size_t nvfios = 0;
11588 for (i = 0; i < def->nhostdevs; i++) {
11589 virDomainHostdevDefPtr tmp = def->hostdevs[i];
11590 if (tmp->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
11591 tmp->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
11592 tmp->source.subsys.u.pci.backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
11593 nvfios++;
11596 if (nvfios == 0)
11597 includeVFIO = true;
11598 } else {
11599 includeVFIO = true;
11602 break;
11604 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
11605 if (dev->missing)
11606 break;
11607 usb = virUSBDeviceNew(usbsrc->bus,
11608 usbsrc->device,
11609 NULL);
11610 if (!usb)
11611 goto cleanup;
11613 if (!(tmpPath = (char *)virUSBDeviceGetPath(usb)))
11614 goto cleanup;
11615 perm = VIR_CGROUP_DEVICE_RW;
11616 break;
11618 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
11619 if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
11620 virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
11621 VIR_DEBUG("Not updating /dev for hostdev iSCSI path '%s'", iscsisrc->src->path);
11622 } else {
11623 virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
11624 scsi = virSCSIDeviceNew(NULL,
11625 scsihostsrc->adapter,
11626 scsihostsrc->bus,
11627 scsihostsrc->target,
11628 scsihostsrc->unit,
11629 dev->readonly,
11630 dev->shareable);
11632 if (!scsi)
11633 goto cleanup;
11635 if (!(tmpPath = (char *)virSCSIDeviceGetPath(scsi)))
11636 goto cleanup;
11637 perm = virSCSIDeviceGetReadonly(scsi) ?
11638 VIR_CGROUP_DEVICE_READ : VIR_CGROUP_DEVICE_RW;
11640 break;
11642 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST: {
11643 if (hostsrc->protocol ==
11644 VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_HOST_PROTOCOL_TYPE_VHOST) {
11645 if (!(host = virSCSIVHostDeviceNew(hostsrc->wwpn)))
11646 goto cleanup;
11648 if (!(tmpPath = (char *)virSCSIVHostDeviceGetPath(host)))
11649 goto cleanup;
11650 perm = VIR_CGROUP_DEVICE_RW;
11652 break;
11655 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV:
11656 if (!(tmpPath = virMediatedDeviceGetIOMMUGroupDev(mdevsrc->uuidstr)))
11657 goto cleanup;
11659 freeTmpPath = true;
11660 includeVFIO = true;
11661 perm = VIR_CGROUP_DEVICE_RW;
11662 break;
11663 case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
11664 break;
11666 break;
11668 case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
11669 case VIR_DOMAIN_HOSTDEV_MODE_LAST:
11670 /* nada */
11671 break;
11674 if (tmpPath) {
11675 size_t toAlloc = 1;
11677 if (includeVFIO)
11678 toAlloc = 2;
11680 if (VIR_ALLOC_N(tmpPaths, toAlloc) < 0 ||
11681 VIR_ALLOC_N(tmpPerms, toAlloc) < 0 ||
11682 VIR_STRDUP(tmpPaths[0], tmpPath) < 0)
11683 goto cleanup;
11684 tmpNpaths = toAlloc;
11685 tmpPerms[0] = perm;
11687 if (includeVFIO) {
11688 if (VIR_STRDUP(tmpPaths[1], DEV_VFIO) < 0)
11689 goto cleanup;
11690 tmpPerms[1] = VIR_CGROUP_DEVICE_RW;
11694 *npaths = tmpNpaths;
11695 tmpNpaths = 0;
11696 *path = tmpPaths;
11697 tmpPaths = NULL;
11698 if (perms) {
11699 *perms = tmpPerms;
11700 tmpPerms = NULL;
11702 ret = 0;
11703 cleanup:
11704 virStringListFreeCount(tmpPaths, tmpNpaths);
11705 VIR_FREE(tmpPerms);
11706 virPCIDeviceFree(pci);
11707 virUSBDeviceFree(usb);
11708 virSCSIDeviceFree(scsi);
11709 virSCSIVHostDeviceFree(host);
11710 if (freeTmpPath)
11711 VIR_FREE(tmpPath);
11712 return ret;
11717 * qemuDomainGetPreservedMountPath:
11718 * @cfg: driver configuration data
11719 * @vm: domain object
11720 * @mountpoint: mount point path to convert
11722 * For given @mountpoint return new path where the mount point
11723 * should be moved temporarily whilst building the namespace.
11725 * Returns: allocated string on success which the caller must free,
11726 * NULL on failure.
11728 static char *
11729 qemuDomainGetPreservedMountPath(virQEMUDriverConfigPtr cfg,
11730 virDomainObjPtr vm,
11731 const char *mountpoint)
11733 char *path = NULL;
11734 char *tmp;
11735 const char *suffix = mountpoint + strlen(DEVPREFIX);
11736 char *domname = virDomainDefGetShortName(vm->def);
11737 size_t off;
11739 if (!domname)
11740 return NULL;
11742 if (STREQ(mountpoint, "/dev"))
11743 suffix = "dev";
11745 if (virAsprintf(&path, "%s/%s.%s",
11746 cfg->stateDir, domname, suffix) < 0)
11747 goto cleanup;
11749 /* Now consider that @mountpoint is "/dev/blah/blah2".
11750 * @suffix then points to "blah/blah2". However, caller
11751 * expects all the @paths to be the same depth. The
11752 * caller doesn't always do `mkdir -p` but sometimes bare
11753 * `touch`. Therefore fix all the suffixes. */
11754 off = strlen(path) - strlen(suffix);
11756 tmp = path + off;
11757 while (*tmp) {
11758 if (*tmp == '/')
11759 *tmp = '.';
11760 tmp++;
11763 cleanup:
11764 VIR_FREE(domname);
11765 return path;
11770 * qemuDomainGetPreservedMounts:
11772 * Process list of mounted filesystems and:
11773 * a) save all FSs mounted under /dev to @devPath
11774 * b) generate backup path for all the entries in a)
11776 * Any of the return pointers can be NULL.
11778 * Returns 0 on success, -1 otherwise (with error reported)
11780 static int
11781 qemuDomainGetPreservedMounts(virQEMUDriverConfigPtr cfg,
11782 virDomainObjPtr vm,
11783 char ***devPath,
11784 char ***devSavePath,
11785 size_t *ndevPath)
11787 char **paths = NULL, **mounts = NULL;
11788 size_t i, j, nmounts;
11790 if (virFileGetMountSubtree(PROC_MOUNTS, "/dev",
11791 &mounts, &nmounts) < 0)
11792 goto error;
11794 if (!nmounts) {
11795 if (ndevPath)
11796 *ndevPath = 0;
11797 return 0;
11800 /* There can be nested mount points. For instance
11801 * /dev/shm/blah can be a mount point and /dev/shm too. It
11802 * doesn't make much sense to return the former path because
11803 * caller preserves the latter (and with that the former
11804 * too). Therefore prune nested mount points.
11805 * NB mounts[0] is "/dev". Should we start the outer loop
11806 * from the beginning of the array all we'd be left with is
11807 * just the first element. Think about it.
11809 for (i = 1; i < nmounts; i++) {
11810 j = i + 1;
11811 while (j < nmounts) {
11812 char *c = STRSKIP(mounts[j], mounts[i]);
11814 if (c && (*c == '/' || *c == '\0')) {
11815 VIR_DEBUG("Dropping path %s because of %s", mounts[j], mounts[i]);
11816 VIR_DELETE_ELEMENT(mounts, j, nmounts);
11817 } else {
11818 j++;
11823 if (VIR_ALLOC_N(paths, nmounts) < 0)
11824 goto error;
11826 for (i = 0; i < nmounts; i++) {
11827 if (!(paths[i] = qemuDomainGetPreservedMountPath(cfg, vm, mounts[i])))
11828 goto error;
11831 if (devPath)
11832 *devPath = mounts;
11833 else
11834 virStringListFreeCount(mounts, nmounts);
11836 if (devSavePath)
11837 *devSavePath = paths;
11838 else
11839 virStringListFreeCount(paths, nmounts);
11841 if (ndevPath)
11842 *ndevPath = nmounts;
11844 return 0;
11846 error:
11847 virStringListFreeCount(mounts, nmounts);
11848 virStringListFreeCount(paths, nmounts);
11849 return -1;
11853 struct qemuDomainCreateDeviceData {
11854 const char *path; /* Path to temp new /dev location */
11855 char * const *devMountsPath;
11856 size_t ndevMountsPath;
11860 static int
11861 qemuDomainCreateDeviceRecursive(const char *device,
11862 const struct qemuDomainCreateDeviceData *data,
11863 bool allow_noent,
11864 unsigned int ttl)
11866 char *devicePath = NULL;
11867 char *target = NULL;
11868 struct stat sb;
11869 int ret = -1;
11870 bool isLink = false;
11871 bool isDev = false;
11872 bool isReg = false;
11873 bool isDir = false;
11874 bool create = false;
11875 #ifdef WITH_SELINUX
11876 char *tcon = NULL;
11877 #endif
11879 if (!ttl) {
11880 virReportSystemError(ELOOP,
11881 _("Too many levels of symbolic links: %s"),
11882 device);
11883 return ret;
11886 if (lstat(device, &sb) < 0) {
11887 if (errno == ENOENT && allow_noent) {
11888 /* Ignore non-existent device. */
11889 return 0;
11891 virReportSystemError(errno, _("Unable to stat %s"), device);
11892 return ret;
11895 isLink = S_ISLNK(sb.st_mode);
11896 isDev = S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode);
11897 isReg = S_ISREG(sb.st_mode) || S_ISFIFO(sb.st_mode) || S_ISSOCK(sb.st_mode);
11898 isDir = S_ISDIR(sb.st_mode);
11900 /* Here, @device might be whatever path in the system. We
11901 * should create the path in the namespace iff it's "/dev"
11902 * prefixed. However, if it is a symlink, we need to traverse
11903 * it too (it might point to something in "/dev"). Just
11904 * consider:
11906 * /var/sym1 -> /var/sym2 -> /dev/sda (because users can)
11908 * This means, "/var/sym1" is not created (it's shared with
11909 * the parent namespace), nor "/var/sym2", but "/dev/sda".
11911 * TODO Remove all `.' and `..' from the @device path.
11912 * Otherwise we might get fooled with `/dev/../var/my_image'.
11913 * For now, lets hope callers play nice.
11915 if (STRPREFIX(device, DEVPREFIX)) {
11916 size_t i;
11918 for (i = 0; i < data->ndevMountsPath; i++) {
11919 if (STREQ(data->devMountsPath[i], "/dev"))
11920 continue;
11921 if (STRPREFIX(device, data->devMountsPath[i]))
11922 break;
11925 if (i == data->ndevMountsPath) {
11926 /* Okay, @device is in /dev but not in any mount point under /dev.
11927 * Create it. */
11928 if (virAsprintf(&devicePath, "%s/%s",
11929 data->path, device + strlen(DEVPREFIX)) < 0)
11930 goto cleanup;
11932 if (virFileMakeParentPath(devicePath) < 0) {
11933 virReportSystemError(errno,
11934 _("Unable to create %s"),
11935 devicePath);
11936 goto cleanup;
11938 VIR_DEBUG("Creating dev %s", device);
11939 create = true;
11940 } else {
11941 VIR_DEBUG("Skipping dev %s because of %s mount point",
11942 device, data->devMountsPath[i]);
11946 if (isLink) {
11947 /* We are dealing with a symlink. Create a dangling symlink and descend
11948 * down one level which hopefully creates the symlink's target. */
11949 if (virFileReadLink(device, &target) < 0) {
11950 virReportSystemError(errno,
11951 _("unable to resolve symlink %s"),
11952 device);
11953 goto cleanup;
11956 if (create &&
11957 symlink(target, devicePath) < 0) {
11958 if (errno == EEXIST) {
11959 ret = 0;
11960 } else {
11961 virReportSystemError(errno,
11962 _("unable to create symlink %s"),
11963 devicePath);
11965 goto cleanup;
11968 /* Tricky part. If the target starts with a slash then we need to take
11969 * it as it is. Otherwise we need to replace the last component in the
11970 * original path with the link target:
11971 * /dev/rtc -> rtc0 (want /dev/rtc0)
11972 * /dev/disk/by-id/ata-SanDisk_SDSSDXPS480G_161101402485 -> ../../sda
11973 * (want /dev/disk/by-id/../../sda)
11974 * /dev/stdout -> /proc/self/fd/1 (no change needed)
11976 if (IS_RELATIVE_FILE_NAME(target)) {
11977 char *c = NULL, *tmp = NULL, *devTmp = NULL;
11979 if (VIR_STRDUP(devTmp, device) < 0)
11980 goto cleanup;
11982 if ((c = strrchr(devTmp, '/')))
11983 *(c + 1) = '\0';
11985 if (virAsprintf(&tmp, "%s%s", devTmp, target) < 0) {
11986 VIR_FREE(devTmp);
11987 goto cleanup;
11989 VIR_FREE(devTmp);
11990 VIR_FREE(target);
11991 VIR_STEAL_PTR(target, tmp);
11994 if (qemuDomainCreateDeviceRecursive(target, data,
11995 allow_noent, ttl - 1) < 0)
11996 goto cleanup;
11997 } else if (isDev) {
11998 if (create &&
11999 mknod(devicePath, sb.st_mode, sb.st_rdev) < 0) {
12000 if (errno == EEXIST) {
12001 ret = 0;
12002 } else {
12003 virReportSystemError(errno,
12004 _("Failed to make device %s"),
12005 devicePath);
12007 goto cleanup;
12009 } else if (isReg) {
12010 if (create &&
12011 virFileTouch(devicePath, sb.st_mode) < 0)
12012 goto cleanup;
12013 /* Just create the file here so that code below sets
12014 * proper owner and mode. Bind mount only after that. */
12015 } else if (isDir) {
12016 if (create &&
12017 virFileMakePathWithMode(devicePath, sb.st_mode) < 0)
12018 goto cleanup;
12019 } else {
12020 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
12021 _("unsupported device type %s 0%o"),
12022 device, sb.st_mode);
12023 goto cleanup;
12026 if (!create) {
12027 ret = 0;
12028 goto cleanup;
12031 if (lchown(devicePath, sb.st_uid, sb.st_gid) < 0) {
12032 virReportSystemError(errno,
12033 _("Failed to chown device %s"),
12034 devicePath);
12035 goto cleanup;
12038 /* Symlinks don't have mode */
12039 if (!isLink &&
12040 chmod(devicePath, sb.st_mode) < 0) {
12041 virReportSystemError(errno,
12042 _("Failed to set permissions for device %s"),
12043 devicePath);
12044 goto cleanup;
12047 /* Symlinks don't have ACLs. */
12048 if (!isLink &&
12049 virFileCopyACLs(device, devicePath) < 0 &&
12050 errno != ENOTSUP) {
12051 virReportSystemError(errno,
12052 _("Failed to copy ACLs on device %s"),
12053 devicePath);
12054 goto cleanup;
12057 #ifdef WITH_SELINUX
12058 if (lgetfilecon_raw(device, &tcon) < 0 &&
12059 (errno != ENOTSUP && errno != ENODATA)) {
12060 virReportSystemError(errno,
12061 _("Unable to get SELinux label from %s"),
12062 device);
12063 goto cleanup;
12066 if (tcon &&
12067 lsetfilecon_raw(devicePath, (VIR_SELINUX_CTX_CONST char *)tcon) < 0) {
12068 VIR_WARNINGS_NO_WLOGICALOP_EQUAL_EXPR
12069 if (errno != EOPNOTSUPP && errno != ENOTSUP) {
12070 VIR_WARNINGS_RESET
12071 virReportSystemError(errno,
12072 _("Unable to set SELinux label on %s"),
12073 devicePath);
12074 goto cleanup;
12077 #endif
12079 /* Finish mount process started earlier. */
12080 if ((isReg || isDir) &&
12081 virFileBindMountDevice(device, devicePath) < 0)
12082 goto cleanup;
12084 ret = 0;
12085 cleanup:
12086 VIR_FREE(target);
12087 VIR_FREE(devicePath);
12088 #ifdef WITH_SELINUX
12089 freecon(tcon);
12090 #endif
12091 return ret;
12095 static int
12096 qemuDomainCreateDevice(const char *device,
12097 const struct qemuDomainCreateDeviceData *data,
12098 bool allow_noent)
12100 long symloop_max = sysconf(_SC_SYMLOOP_MAX);
12102 return qemuDomainCreateDeviceRecursive(device, data,
12103 allow_noent, symloop_max);
12107 static int
12108 qemuDomainPopulateDevices(virQEMUDriverConfigPtr cfg,
12109 virDomainObjPtr vm ATTRIBUTE_UNUSED,
12110 const struct qemuDomainCreateDeviceData *data)
12112 const char *const *devices = (const char *const *) cfg->cgroupDeviceACL;
12113 size_t i;
12114 int ret = -1;
12116 if (!devices)
12117 devices = defaultDeviceACL;
12119 for (i = 0; devices[i]; i++) {
12120 if (qemuDomainCreateDevice(devices[i], data, true) < 0)
12121 goto cleanup;
12124 ret = 0;
12125 cleanup:
12126 return ret;
12130 static int
12131 qemuDomainSetupDev(virQEMUDriverConfigPtr cfg,
12132 virSecurityManagerPtr mgr,
12133 virDomainObjPtr vm,
12134 const struct qemuDomainCreateDeviceData *data)
12136 char *mount_options = NULL;
12137 char *opts = NULL;
12138 int ret = -1;
12140 VIR_DEBUG("Setting up /dev/ for domain %s", vm->def->name);
12142 mount_options = qemuSecurityGetMountOptions(mgr, vm->def);
12144 if (!mount_options &&
12145 VIR_STRDUP(mount_options, "") < 0)
12146 goto cleanup;
12149 * tmpfs is limited to 64kb, since we only have device nodes in there
12150 * and don't want to DOS the entire OS RAM usage
12152 if (virAsprintf(&opts,
12153 "mode=755,size=65536%s", mount_options) < 0)
12154 goto cleanup;
12156 if (virFileSetupDev(data->path, opts) < 0)
12157 goto cleanup;
12159 if (qemuDomainPopulateDevices(cfg, vm, data) < 0)
12160 goto cleanup;
12162 ret = 0;
12163 cleanup:
12164 VIR_FREE(opts);
12165 VIR_FREE(mount_options);
12166 return ret;
12170 static int
12171 qemuDomainSetupDisk(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12172 virDomainDiskDefPtr disk,
12173 const struct qemuDomainCreateDeviceData *data)
12175 virStorageSourcePtr next;
12176 char *dst = NULL;
12177 int ret = -1;
12179 for (next = disk->src; virStorageSourceIsBacking(next); next = next->backingStore) {
12180 if (!next->path || !virStorageSourceIsLocalStorage(next)) {
12181 /* Not creating device. Just continue. */
12182 continue;
12185 if (qemuDomainCreateDevice(next->path, data, false) < 0)
12186 goto cleanup;
12189 /* qemu-pr-helper might require access to /dev/mapper/control. */
12190 if (disk->src->pr &&
12191 qemuDomainCreateDevice(DEVICE_MAPPER_CONTROL_PATH, data, true) < 0)
12192 goto cleanup;
12194 ret = 0;
12195 cleanup:
12196 VIR_FREE(dst);
12197 return ret;
12201 static int
12202 qemuDomainSetupAllDisks(virQEMUDriverConfigPtr cfg,
12203 virDomainObjPtr vm,
12204 const struct qemuDomainCreateDeviceData *data)
12206 size_t i;
12207 VIR_DEBUG("Setting up disks");
12209 for (i = 0; i < vm->def->ndisks; i++) {
12210 if (qemuDomainSetupDisk(cfg,
12211 vm->def->disks[i],
12212 data) < 0)
12213 return -1;
12216 VIR_DEBUG("Setup all disks");
12217 return 0;
12221 static int
12222 qemuDomainSetupHostdev(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12223 virDomainHostdevDefPtr dev,
12224 const struct qemuDomainCreateDeviceData *data)
12226 int ret = -1;
12227 char **path = NULL;
12228 size_t i, npaths = 0;
12230 if (qemuDomainGetHostdevPath(NULL, dev, false, &npaths, &path, NULL) < 0)
12231 goto cleanup;
12233 for (i = 0; i < npaths; i++) {
12234 if (qemuDomainCreateDevice(path[i], data, false) < 0)
12235 goto cleanup;
12238 ret = 0;
12239 cleanup:
12240 for (i = 0; i < npaths; i++)
12241 VIR_FREE(path[i]);
12242 VIR_FREE(path);
12243 return ret;
12247 static int
12248 qemuDomainSetupAllHostdevs(virQEMUDriverConfigPtr cfg,
12249 virDomainObjPtr vm,
12250 const struct qemuDomainCreateDeviceData *data)
12252 size_t i;
12254 VIR_DEBUG("Setting up hostdevs");
12255 for (i = 0; i < vm->def->nhostdevs; i++) {
12256 if (qemuDomainSetupHostdev(cfg,
12257 vm->def->hostdevs[i],
12258 data) < 0)
12259 return -1;
12261 VIR_DEBUG("Setup all hostdevs");
12262 return 0;
12266 static int
12267 qemuDomainSetupMemory(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12268 virDomainMemoryDefPtr mem,
12269 const struct qemuDomainCreateDeviceData *data)
12271 if (mem->model != VIR_DOMAIN_MEMORY_MODEL_NVDIMM)
12272 return 0;
12274 return qemuDomainCreateDevice(mem->nvdimmPath, data, false);
12278 static int
12279 qemuDomainSetupAllMemories(virQEMUDriverConfigPtr cfg,
12280 virDomainObjPtr vm,
12281 const struct qemuDomainCreateDeviceData *data)
12283 size_t i;
12285 VIR_DEBUG("Setting up memories");
12286 for (i = 0; i < vm->def->nmems; i++) {
12287 if (qemuDomainSetupMemory(cfg,
12288 vm->def->mems[i],
12289 data) < 0)
12290 return -1;
12292 VIR_DEBUG("Setup all memories");
12293 return 0;
12297 static int
12298 qemuDomainSetupChardev(virDomainDefPtr def ATTRIBUTE_UNUSED,
12299 virDomainChrDefPtr dev,
12300 void *opaque)
12302 const struct qemuDomainCreateDeviceData *data = opaque;
12303 const char *path = NULL;
12305 if (!(path = virDomainChrSourceDefGetPath(dev->source)))
12306 return 0;
12308 /* Socket created by qemu. It doesn't exist upfront. */
12309 if (dev->source->type == VIR_DOMAIN_CHR_TYPE_UNIX &&
12310 dev->source->data.nix.listen)
12311 return 0;
12313 return qemuDomainCreateDevice(path, data, true);
12317 static int
12318 qemuDomainSetupAllChardevs(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12319 virDomainObjPtr vm,
12320 const struct qemuDomainCreateDeviceData *data)
12322 VIR_DEBUG("Setting up chardevs");
12324 if (virDomainChrDefForeach(vm->def,
12325 true,
12326 qemuDomainSetupChardev,
12327 (void *)data) < 0)
12328 return -1;
12330 VIR_DEBUG("Setup all chardevs");
12331 return 0;
12335 static int
12336 qemuDomainSetupTPM(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12337 virDomainObjPtr vm,
12338 const struct qemuDomainCreateDeviceData *data)
12340 virDomainTPMDefPtr dev = vm->def->tpm;
12342 if (!dev)
12343 return 0;
12345 VIR_DEBUG("Setting up TPM");
12347 switch (dev->type) {
12348 case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
12349 if (qemuDomainCreateDevice(dev->data.passthrough.source.data.file.path,
12350 data, false) < 0)
12351 return -1;
12352 break;
12354 case VIR_DOMAIN_TPM_TYPE_EMULATOR:
12355 case VIR_DOMAIN_TPM_TYPE_LAST:
12356 /* nada */
12357 break;
12360 VIR_DEBUG("Setup TPM");
12361 return 0;
12365 static int
12366 qemuDomainSetupGraphics(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12367 virDomainGraphicsDefPtr gfx,
12368 const struct qemuDomainCreateDeviceData *data)
12370 const char *rendernode = virDomainGraphicsGetRenderNode(gfx);
12372 if (!rendernode)
12373 return 0;
12375 return qemuDomainCreateDevice(rendernode, data, false);
12379 static int
12380 qemuDomainSetupAllGraphics(virQEMUDriverConfigPtr cfg,
12381 virDomainObjPtr vm,
12382 const struct qemuDomainCreateDeviceData *data)
12384 size_t i;
12386 VIR_DEBUG("Setting up graphics");
12387 for (i = 0; i < vm->def->ngraphics; i++) {
12388 if (qemuDomainSetupGraphics(cfg,
12389 vm->def->graphics[i],
12390 data) < 0)
12391 return -1;
12394 VIR_DEBUG("Setup all graphics");
12395 return 0;
12399 static int
12400 qemuDomainSetupInput(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12401 virDomainInputDefPtr input,
12402 const struct qemuDomainCreateDeviceData *data)
12404 const char *path = virDomainInputDefGetPath(input);
12406 if (path && qemuDomainCreateDevice(path, data, false) < 0)
12407 return -1;
12409 return 0;
12413 static int
12414 qemuDomainSetupAllInputs(virQEMUDriverConfigPtr cfg,
12415 virDomainObjPtr vm,
12416 const struct qemuDomainCreateDeviceData *data)
12418 size_t i;
12420 VIR_DEBUG("Setting up inputs");
12421 for (i = 0; i < vm->def->ninputs; i++) {
12422 if (qemuDomainSetupInput(cfg,
12423 vm->def->inputs[i],
12424 data) < 0)
12425 return -1;
12427 VIR_DEBUG("Setup all inputs");
12428 return 0;
12432 static int
12433 qemuDomainSetupRNG(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12434 virDomainRNGDefPtr rng,
12435 const struct qemuDomainCreateDeviceData *data)
12437 switch ((virDomainRNGBackend) rng->backend) {
12438 case VIR_DOMAIN_RNG_BACKEND_RANDOM:
12439 if (qemuDomainCreateDevice(rng->source.file, data, false) < 0)
12440 return -1;
12442 case VIR_DOMAIN_RNG_BACKEND_EGD:
12443 case VIR_DOMAIN_RNG_BACKEND_LAST:
12444 /* nada */
12445 break;
12448 return 0;
12452 static int
12453 qemuDomainSetupAllRNGs(virQEMUDriverConfigPtr cfg,
12454 virDomainObjPtr vm,
12455 const struct qemuDomainCreateDeviceData *data)
12457 size_t i;
12459 VIR_DEBUG("Setting up RNGs");
12460 for (i = 0; i < vm->def->nrngs; i++) {
12461 if (qemuDomainSetupRNG(cfg,
12462 vm->def->rngs[i],
12463 data) < 0)
12464 return -1;
12467 VIR_DEBUG("Setup all RNGs");
12468 return 0;
12472 static int
12473 qemuDomainSetupLoader(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12474 virDomainObjPtr vm,
12475 const struct qemuDomainCreateDeviceData *data)
12477 virDomainLoaderDefPtr loader = vm->def->os.loader;
12478 int ret = -1;
12480 VIR_DEBUG("Setting up loader");
12482 if (loader) {
12483 switch ((virDomainLoader) loader->type) {
12484 case VIR_DOMAIN_LOADER_TYPE_ROM:
12485 if (qemuDomainCreateDevice(loader->path, data, false) < 0)
12486 goto cleanup;
12487 break;
12489 case VIR_DOMAIN_LOADER_TYPE_PFLASH:
12490 if (qemuDomainCreateDevice(loader->path, data, false) < 0)
12491 goto cleanup;
12493 if (loader->nvram &&
12494 qemuDomainCreateDevice(loader->nvram, data, false) < 0)
12495 goto cleanup;
12496 break;
12498 case VIR_DOMAIN_LOADER_TYPE_NONE:
12499 case VIR_DOMAIN_LOADER_TYPE_LAST:
12500 break;
12504 VIR_DEBUG("Setup loader");
12505 ret = 0;
12506 cleanup:
12507 return ret;
12511 static int
12512 qemuDomainSetupLaunchSecurity(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
12513 virDomainObjPtr vm,
12514 const struct qemuDomainCreateDeviceData *data)
12516 virDomainSEVDefPtr sev = vm->def->sev;
12518 if (!sev || sev->sectype != VIR_DOMAIN_LAUNCH_SECURITY_SEV)
12519 return 0;
12521 VIR_DEBUG("Setting up launch security");
12523 if (qemuDomainCreateDevice(DEV_SEV, data, false) < 0)
12524 return -1;
12526 VIR_DEBUG("Set up launch security");
12527 return 0;
12532 qemuDomainBuildNamespace(virQEMUDriverConfigPtr cfg,
12533 virSecurityManagerPtr mgr,
12534 virDomainObjPtr vm)
12536 struct qemuDomainCreateDeviceData data;
12537 char *devPath = NULL;
12538 char **devMountsPath = NULL, **devMountsSavePath = NULL;
12539 size_t ndevMountsPath = 0, i;
12540 int ret = -1;
12542 if (!qemuDomainNamespaceEnabled(vm, QEMU_DOMAIN_NS_MOUNT)) {
12543 ret = 0;
12544 goto cleanup;
12547 if (qemuDomainGetPreservedMounts(cfg, vm,
12548 &devMountsPath, &devMountsSavePath,
12549 &ndevMountsPath) < 0)
12550 goto cleanup;
12552 for (i = 0; i < ndevMountsPath; i++) {
12553 if (STREQ(devMountsPath[i], "/dev")) {
12554 devPath = devMountsSavePath[i];
12555 break;
12559 if (!devPath) {
12560 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
12561 _("Unable to find any /dev mount"));
12562 goto cleanup;
12565 data.path = devPath;
12566 data.devMountsPath = devMountsPath;
12567 data.ndevMountsPath = ndevMountsPath;
12569 if (virProcessSetupPrivateMountNS() < 0)
12570 goto cleanup;
12572 if (qemuDomainSetupDev(cfg, mgr, vm, &data) < 0)
12573 goto cleanup;
12575 if (qemuDomainSetupAllDisks(cfg, vm, &data) < 0)
12576 goto cleanup;
12578 if (qemuDomainSetupAllHostdevs(cfg, vm, &data) < 0)
12579 goto cleanup;
12581 if (qemuDomainSetupAllMemories(cfg, vm, &data) < 0)
12582 goto cleanup;
12584 if (qemuDomainSetupAllChardevs(cfg, vm, &data) < 0)
12585 goto cleanup;
12587 if (qemuDomainSetupTPM(cfg, vm, &data) < 0)
12588 goto cleanup;
12590 if (qemuDomainSetupAllGraphics(cfg, vm, &data) < 0)
12591 goto cleanup;
12593 if (qemuDomainSetupAllInputs(cfg, vm, &data) < 0)
12594 goto cleanup;
12596 if (qemuDomainSetupAllRNGs(cfg, vm, &data) < 0)
12597 goto cleanup;
12599 if (qemuDomainSetupLoader(cfg, vm, &data) < 0)
12600 goto cleanup;
12602 if (qemuDomainSetupLaunchSecurity(cfg, vm, &data) < 0)
12603 goto cleanup;
12605 /* Save some mount points because we want to share them with the host */
12606 for (i = 0; i < ndevMountsPath; i++) {
12607 struct stat sb;
12609 if (devMountsSavePath[i] == devPath)
12610 continue;
12612 if (stat(devMountsPath[i], &sb) < 0) {
12613 virReportSystemError(errno,
12614 _("Unable to stat: %s"),
12615 devMountsPath[i]);
12616 goto cleanup;
12619 /* At this point, devMountsPath is either:
12620 * a file (regular or special), or
12621 * a directory. */
12622 if ((S_ISDIR(sb.st_mode) && virFileMakePath(devMountsSavePath[i]) < 0) ||
12623 (!S_ISDIR(sb.st_mode) && virFileTouch(devMountsSavePath[i], sb.st_mode) < 0)) {
12624 virReportSystemError(errno,
12625 _("Failed to create %s"),
12626 devMountsSavePath[i]);
12627 goto cleanup;
12630 if (virFileMoveMount(devMountsPath[i], devMountsSavePath[i]) < 0)
12631 goto cleanup;
12634 if (virFileMoveMount(devPath, "/dev") < 0)
12635 goto cleanup;
12637 for (i = 0; i < ndevMountsPath; i++) {
12638 struct stat sb;
12640 if (devMountsSavePath[i] == devPath)
12641 continue;
12643 if (stat(devMountsSavePath[i], &sb) < 0) {
12644 virReportSystemError(errno,
12645 _("Unable to stat: %s"),
12646 devMountsSavePath[i]);
12647 goto cleanup;
12650 if (S_ISDIR(sb.st_mode)) {
12651 if (virFileMakePath(devMountsPath[i]) < 0) {
12652 virReportSystemError(errno, _("Cannot create %s"),
12653 devMountsPath[i]);
12654 goto cleanup;
12656 } else {
12657 if (virFileMakeParentPath(devMountsPath[i]) < 0 ||
12658 virFileTouch(devMountsPath[i], sb.st_mode) < 0) {
12659 virReportSystemError(errno, _("Cannot create %s"),
12660 devMountsPath[i]);
12661 goto cleanup;
12665 if (virFileMoveMount(devMountsSavePath[i], devMountsPath[i]) < 0)
12666 goto cleanup;
12669 ret = 0;
12670 cleanup:
12671 for (i = 0; i < ndevMountsPath; i++) {
12672 /* The path can be either a regular file or a dir. */
12673 if (virFileIsDir(devMountsSavePath[i]))
12674 rmdir(devMountsSavePath[i]);
12675 else
12676 unlink(devMountsSavePath[i]);
12678 virStringListFreeCount(devMountsPath, ndevMountsPath);
12679 virStringListFreeCount(devMountsSavePath, ndevMountsPath);
12680 return ret;
12685 qemuDomainCreateNamespace(virQEMUDriverPtr driver,
12686 virDomainObjPtr vm)
12688 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
12689 int ret = -1;
12691 if (virBitmapIsBitSet(cfg->namespaces, QEMU_DOMAIN_NS_MOUNT) &&
12692 qemuDomainEnableNamespace(vm, QEMU_DOMAIN_NS_MOUNT) < 0)
12693 goto cleanup;
12695 ret = 0;
12696 cleanup:
12697 virObjectUnref(cfg);
12698 return ret;
12702 void
12703 qemuDomainDestroyNamespace(virQEMUDriverPtr driver ATTRIBUTE_UNUSED,
12704 virDomainObjPtr vm)
12706 if (qemuDomainNamespaceEnabled(vm, QEMU_DOMAIN_NS_MOUNT))
12707 qemuDomainDisableNamespace(vm, QEMU_DOMAIN_NS_MOUNT);
12711 bool
12712 qemuDomainNamespaceAvailable(qemuDomainNamespace ns ATTRIBUTE_UNUSED)
12714 #if !defined(__linux__)
12715 /* Namespaces are Linux specific. */
12716 return false;
12718 #else /* defined(__linux__) */
12720 switch (ns) {
12721 case QEMU_DOMAIN_NS_MOUNT:
12722 # if !defined(HAVE_SYS_ACL_H) || !defined(WITH_SELINUX)
12723 /* We can't create the exact copy of paths if either of
12724 * these is not available. */
12725 return false;
12726 # else
12727 if (virProcessNamespaceAvailable(VIR_PROCESS_NAMESPACE_MNT) < 0)
12728 return false;
12729 # endif
12730 break;
12731 case QEMU_DOMAIN_NS_LAST:
12732 break;
12735 return true;
12736 #endif /* defined(__linux__) */
12740 struct qemuDomainAttachDeviceMknodData {
12741 virQEMUDriverPtr driver;
12742 virDomainObjPtr vm;
12743 const char *file;
12744 const char *target;
12745 struct stat sb;
12746 void *acl;
12747 #ifdef WITH_SELINUX
12748 char *tcon;
12749 #endif
12753 /* Our way of creating devices is highly linux specific */
12754 #if defined(__linux__)
12755 static int
12756 qemuDomainAttachDeviceMknodHelper(pid_t pid ATTRIBUTE_UNUSED,
12757 void *opaque)
12759 struct qemuDomainAttachDeviceMknodData *data = opaque;
12760 int ret = -1;
12761 bool delDevice = false;
12762 bool isLink = S_ISLNK(data->sb.st_mode);
12763 bool isDev = S_ISCHR(data->sb.st_mode) || S_ISBLK(data->sb.st_mode);
12764 bool isReg = S_ISREG(data->sb.st_mode) || S_ISFIFO(data->sb.st_mode) || S_ISSOCK(data->sb.st_mode);
12765 bool isDir = S_ISDIR(data->sb.st_mode);
12767 qemuSecurityPostFork(data->driver->securityManager);
12769 if (virFileMakeParentPath(data->file) < 0) {
12770 virReportSystemError(errno,
12771 _("Unable to create %s"), data->file);
12772 goto cleanup;
12775 if (isLink) {
12776 VIR_DEBUG("Creating symlink %s -> %s", data->file, data->target);
12778 /* First, unlink the symlink target. Symlinks change and
12779 * therefore we have no guarantees that pre-existing
12780 * symlink is still valid. */
12781 if (unlink(data->file) < 0 &&
12782 errno != ENOENT) {
12783 virReportSystemError(errno,
12784 _("Unable to remove symlink %s"),
12785 data->file);
12786 goto cleanup;
12789 if (symlink(data->target, data->file) < 0) {
12790 virReportSystemError(errno,
12791 _("Unable to create symlink %s (pointing to %s)"),
12792 data->file, data->target);
12793 goto cleanup;
12794 } else {
12795 delDevice = true;
12797 } else if (isDev) {
12798 VIR_DEBUG("Creating dev %s (%d,%d)",
12799 data->file, major(data->sb.st_rdev), minor(data->sb.st_rdev));
12800 if (mknod(data->file, data->sb.st_mode, data->sb.st_rdev) < 0) {
12801 /* Because we are not removing devices on hotunplug, or
12802 * we might be creating part of backing chain that
12803 * already exist due to a different disk plugged to
12804 * domain, accept EEXIST. */
12805 if (errno != EEXIST) {
12806 virReportSystemError(errno,
12807 _("Unable to create device %s"),
12808 data->file);
12809 goto cleanup;
12811 } else {
12812 delDevice = true;
12814 } else if (isReg || isDir) {
12815 /* We are not cleaning up disks on virDomainDetachDevice
12816 * because disk might be still in use by different disk
12817 * as its backing chain. This might however clash here.
12818 * Therefore do the cleanup here. */
12819 if (umount(data->file) < 0 &&
12820 errno != ENOENT && errno != EINVAL) {
12821 virReportSystemError(errno,
12822 _("Unable to umount %s"),
12823 data->file);
12824 goto cleanup;
12826 if ((isReg && virFileTouch(data->file, data->sb.st_mode) < 0) ||
12827 (isDir && virFileMakePathWithMode(data->file, data->sb.st_mode) < 0))
12828 goto cleanup;
12829 delDevice = true;
12830 /* Just create the file here so that code below sets
12831 * proper owner and mode. Move the mount only after that. */
12832 } else {
12833 virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
12834 _("unsupported device type %s 0%o"),
12835 data->file, data->sb.st_mode);
12836 goto cleanup;
12839 if (lchown(data->file, data->sb.st_uid, data->sb.st_gid) < 0) {
12840 virReportSystemError(errno,
12841 _("Failed to chown device %s"),
12842 data->file);
12843 goto cleanup;
12846 /* Symlinks don't have mode */
12847 if (!isLink &&
12848 chmod(data->file, data->sb.st_mode) < 0) {
12849 virReportSystemError(errno,
12850 _("Failed to set permissions for device %s"),
12851 data->file);
12852 goto cleanup;
12855 /* Symlinks don't have ACLs. */
12856 if (!isLink &&
12857 virFileSetACLs(data->file, data->acl) < 0 &&
12858 errno != ENOTSUP) {
12859 virReportSystemError(errno,
12860 _("Unable to set ACLs on %s"), data->file);
12861 goto cleanup;
12864 # ifdef WITH_SELINUX
12865 if (data->tcon &&
12866 lsetfilecon_raw(data->file, (VIR_SELINUX_CTX_CONST char *)data->tcon) < 0) {
12867 VIR_WARNINGS_NO_WLOGICALOP_EQUAL_EXPR
12868 if (errno != EOPNOTSUPP && errno != ENOTSUP) {
12869 VIR_WARNINGS_RESET
12870 virReportSystemError(errno,
12871 _("Unable to set SELinux label on %s"),
12872 data->file);
12873 goto cleanup;
12876 # endif
12878 /* Finish mount process started earlier. */
12879 if ((isReg || isDir) &&
12880 virFileMoveMount(data->target, data->file) < 0)
12881 goto cleanup;
12883 ret = 0;
12884 cleanup:
12885 if (ret < 0 && delDevice) {
12886 if (isDir)
12887 virFileDeleteTree(data->file);
12888 else
12889 unlink(data->file);
12891 # ifdef WITH_SELINUX
12892 freecon(data->tcon);
12893 # endif
12894 virFileFreeACLs(&data->acl);
12895 return ret;
12899 static int
12900 qemuDomainAttachDeviceMknodRecursive(virQEMUDriverPtr driver,
12901 virDomainObjPtr vm,
12902 const char *file,
12903 char * const *devMountsPath,
12904 size_t ndevMountsPath,
12905 unsigned int ttl)
12907 virQEMUDriverConfigPtr cfg = NULL;
12908 struct qemuDomainAttachDeviceMknodData data;
12909 int ret = -1;
12910 char *target = NULL;
12911 bool isLink;
12912 bool isReg;
12913 bool isDir;
12915 if (!ttl) {
12916 virReportSystemError(ELOOP,
12917 _("Too many levels of symbolic links: %s"),
12918 file);
12919 return ret;
12922 memset(&data, 0, sizeof(data));
12924 data.driver = driver;
12925 data.vm = vm;
12926 data.file = file;
12928 if (lstat(file, &data.sb) < 0) {
12929 virReportSystemError(errno,
12930 _("Unable to access %s"), file);
12931 return ret;
12934 isLink = S_ISLNK(data.sb.st_mode);
12935 isReg = S_ISREG(data.sb.st_mode) || S_ISFIFO(data.sb.st_mode) || S_ISSOCK(data.sb.st_mode);
12936 isDir = S_ISDIR(data.sb.st_mode);
12938 if ((isReg || isDir) && STRPREFIX(file, DEVPREFIX)) {
12939 cfg = virQEMUDriverGetConfig(driver);
12940 if (!(target = qemuDomainGetPreservedMountPath(cfg, vm, file)))
12941 goto cleanup;
12943 if (virFileBindMountDevice(file, target) < 0)
12944 goto cleanup;
12946 data.target = target;
12947 } else if (isLink) {
12948 if (virFileReadLink(file, &target) < 0) {
12949 virReportSystemError(errno,
12950 _("unable to resolve symlink %s"),
12951 file);
12952 return ret;
12955 if (IS_RELATIVE_FILE_NAME(target)) {
12956 char *c = NULL, *tmp = NULL, *fileTmp = NULL;
12958 if (VIR_STRDUP(fileTmp, file) < 0)
12959 goto cleanup;
12961 if ((c = strrchr(fileTmp, '/')))
12962 *(c + 1) = '\0';
12964 if (virAsprintf(&tmp, "%s%s", fileTmp, target) < 0) {
12965 VIR_FREE(fileTmp);
12966 goto cleanup;
12968 VIR_FREE(fileTmp);
12969 VIR_FREE(target);
12970 VIR_STEAL_PTR(target, tmp);
12973 data.target = target;
12976 /* Symlinks don't have ACLs. */
12977 if (!isLink &&
12978 virFileGetACLs(file, &data.acl) < 0 &&
12979 errno != ENOTSUP) {
12980 virReportSystemError(errno,
12981 _("Unable to get ACLs on %s"), file);
12982 goto cleanup;
12985 # ifdef WITH_SELINUX
12986 if (lgetfilecon_raw(file, &data.tcon) < 0 &&
12987 (errno != ENOTSUP && errno != ENODATA)) {
12988 virReportSystemError(errno,
12989 _("Unable to get SELinux label from %s"), file);
12990 goto cleanup;
12992 # endif
12994 if (STRPREFIX(file, DEVPREFIX)) {
12995 size_t i;
12997 for (i = 0; i < ndevMountsPath; i++) {
12998 if (STREQ(devMountsPath[i], "/dev"))
12999 continue;
13000 if (STRPREFIX(file, devMountsPath[i]))
13001 break;
13004 if (i == ndevMountsPath) {
13005 if (qemuSecurityPreFork(driver->securityManager) < 0)
13006 goto cleanup;
13008 if (virProcessRunInMountNamespace(vm->pid,
13009 qemuDomainAttachDeviceMknodHelper,
13010 &data) < 0) {
13011 qemuSecurityPostFork(driver->securityManager);
13012 goto cleanup;
13014 qemuSecurityPostFork(driver->securityManager);
13015 } else {
13016 VIR_DEBUG("Skipping dev %s because of %s mount point",
13017 file, devMountsPath[i]);
13021 if (isLink &&
13022 qemuDomainAttachDeviceMknodRecursive(driver, vm, target,
13023 devMountsPath, ndevMountsPath,
13024 ttl -1) < 0)
13025 goto cleanup;
13027 ret = 0;
13028 cleanup:
13029 # ifdef WITH_SELINUX
13030 freecon(data.tcon);
13031 # endif
13032 virFileFreeACLs(&data.acl);
13033 if (isReg && target)
13034 umount(target);
13035 VIR_FREE(target);
13036 virObjectUnref(cfg);
13037 return ret;
13041 #else /* !defined(__linux__) */
13044 static int
13045 qemuDomainAttachDeviceMknodRecursive(virQEMUDriverPtr driver ATTRIBUTE_UNUSED,
13046 virDomainObjPtr vm ATTRIBUTE_UNUSED,
13047 const char *file ATTRIBUTE_UNUSED,
13048 char * const *devMountsPath ATTRIBUTE_UNUSED,
13049 size_t ndevMountsPath ATTRIBUTE_UNUSED,
13050 unsigned int ttl ATTRIBUTE_UNUSED)
13052 virReportSystemError(ENOSYS, "%s",
13053 _("Namespaces are not supported on this platform."));
13054 return -1;
13058 #endif /* !defined(__linux__) */
13061 static int
13062 qemuDomainAttachDeviceMknod(virQEMUDriverPtr driver,
13063 virDomainObjPtr vm,
13064 const char *file,
13065 char * const *devMountsPath,
13066 size_t ndevMountsPath)
13068 long symloop_max = sysconf(_SC_SYMLOOP_MAX);
13070 return qemuDomainAttachDeviceMknodRecursive(driver, vm, file,
13071 devMountsPath, ndevMountsPath,
13072 symloop_max);
13076 static int
13077 qemuDomainDetachDeviceUnlinkHelper(pid_t pid ATTRIBUTE_UNUSED,
13078 void *opaque)
13080 const char *path = opaque;
13082 VIR_DEBUG("Unlinking %s", path);
13083 if (unlink(path) < 0 && errno != ENOENT) {
13084 virReportSystemError(errno,
13085 _("Unable to remove device %s"), path);
13086 return -1;
13089 return 0;
13093 static int
13094 qemuDomainDetachDeviceUnlink(virQEMUDriverPtr driver ATTRIBUTE_UNUSED,
13095 virDomainObjPtr vm,
13096 const char *file,
13097 char * const *devMountsPath,
13098 size_t ndevMountsPath)
13100 int ret = -1;
13101 size_t i;
13103 if (STRPREFIX(file, DEVPREFIX)) {
13104 for (i = 0; i < ndevMountsPath; i++) {
13105 if (STREQ(devMountsPath[i], "/dev"))
13106 continue;
13107 if (STRPREFIX(file, devMountsPath[i]))
13108 break;
13111 if (i == ndevMountsPath) {
13112 if (virProcessRunInMountNamespace(vm->pid,
13113 qemuDomainDetachDeviceUnlinkHelper,
13114 (void *)file) < 0)
13115 goto cleanup;
13119 ret = 0;
13120 cleanup:
13121 return ret;
13125 static int
13126 qemuDomainNamespaceMknodPaths(virDomainObjPtr vm,
13127 const char **paths,
13128 size_t npaths)
13130 qemuDomainObjPrivatePtr priv = vm->privateData;
13131 virQEMUDriverPtr driver = priv->driver;
13132 virQEMUDriverConfigPtr cfg;
13133 char **devMountsPath = NULL;
13134 size_t ndevMountsPath = 0;
13135 int ret = -1;
13136 size_t i;
13138 if (!qemuDomainNamespaceEnabled(vm, QEMU_DOMAIN_NS_MOUNT) ||
13139 !npaths)
13140 return 0;
13142 cfg = virQEMUDriverGetConfig(driver);
13143 if (qemuDomainGetPreservedMounts(cfg, vm,
13144 &devMountsPath, NULL,
13145 &ndevMountsPath) < 0)
13146 goto cleanup;
13148 for (i = 0; i < npaths; i++) {
13149 if (qemuDomainAttachDeviceMknod(driver,
13151 paths[i],
13152 devMountsPath, ndevMountsPath) < 0)
13153 goto cleanup;
13156 ret = 0;
13157 cleanup:
13158 virStringListFreeCount(devMountsPath, ndevMountsPath);
13159 virObjectUnref(cfg);
13160 return ret;
13164 static int
13165 qemuDomainNamespaceMknodPath(virDomainObjPtr vm,
13166 const char *path)
13168 const char *paths[] = { path };
13170 return qemuDomainNamespaceMknodPaths(vm, paths, 1);
13174 static int
13175 qemuDomainNamespaceUnlinkPaths(virDomainObjPtr vm,
13176 const char **paths,
13177 size_t npaths)
13179 qemuDomainObjPrivatePtr priv = vm->privateData;
13180 virQEMUDriverPtr driver = priv->driver;
13181 virQEMUDriverConfigPtr cfg;
13182 char **devMountsPath = NULL;
13183 size_t ndevMountsPath = 0;
13184 size_t i;
13185 int ret = -1;
13187 if (!qemuDomainNamespaceEnabled(vm, QEMU_DOMAIN_NS_MOUNT) ||
13188 !npaths)
13189 return 0;
13191 cfg = virQEMUDriverGetConfig(driver);
13193 if (qemuDomainGetPreservedMounts(cfg, vm,
13194 &devMountsPath, NULL,
13195 &ndevMountsPath) < 0)
13196 goto cleanup;
13198 for (i = 0; i < npaths; i++) {
13199 if (qemuDomainDetachDeviceUnlink(driver, vm, paths[i],
13200 devMountsPath, ndevMountsPath) < 0)
13201 goto cleanup;
13204 ret = 0;
13205 cleanup:
13206 virStringListFreeCount(devMountsPath, ndevMountsPath);
13207 virObjectUnref(cfg);
13208 return ret;
13212 static int
13213 qemuDomainNamespaceUnlinkPath(virDomainObjPtr vm,
13214 const char *path)
13216 const char *paths[] = { path };
13218 return qemuDomainNamespaceUnlinkPaths(vm, paths, 1);
13223 qemuDomainNamespaceSetupDisk(virDomainObjPtr vm,
13224 virStorageSourcePtr src)
13226 virStorageSourcePtr next;
13227 const char **paths = NULL;
13228 size_t npaths = 0;
13229 char *dmPath = NULL;
13230 int ret = -1;
13232 for (next = src; virStorageSourceIsBacking(next); next = next->backingStore) {
13233 if (virStorageSourceIsEmpty(next) ||
13234 !virStorageSourceIsLocalStorage(next)) {
13235 /* Not creating device. Just continue. */
13236 continue;
13239 if (VIR_APPEND_ELEMENT_COPY(paths, npaths, next->path) < 0)
13240 goto cleanup;
13243 /* qemu-pr-helper might require access to /dev/mapper/control. */
13244 if (src->pr &&
13245 (VIR_STRDUP(dmPath, DEVICE_MAPPER_CONTROL_PATH) < 0 ||
13246 VIR_APPEND_ELEMENT_COPY(paths, npaths, dmPath) < 0))
13247 goto cleanup;
13249 if (qemuDomainNamespaceMknodPaths(vm, paths, npaths) < 0)
13250 goto cleanup;
13252 ret = 0;
13253 cleanup:
13254 VIR_FREE(dmPath);
13255 VIR_FREE(paths);
13256 return ret;
13261 qemuDomainNamespaceTeardownDisk(virDomainObjPtr vm ATTRIBUTE_UNUSED,
13262 virStorageSourcePtr src ATTRIBUTE_UNUSED)
13264 /* While in hotplug case we create the whole backing chain,
13265 * here we must limit ourselves. The disk we want to remove
13266 * might be a part of backing chain of another disk.
13267 * If you are reading these lines and have some spare time
13268 * you can come up with and algorithm that checks for that.
13269 * I don't, therefore: */
13270 return 0;
13275 qemuDomainNamespaceSetupHostdev(virDomainObjPtr vm,
13276 virDomainHostdevDefPtr hostdev)
13278 int ret = -1;
13279 char **paths = NULL;
13280 size_t i, npaths = 0;
13282 if (qemuDomainGetHostdevPath(NULL, hostdev, false, &npaths, &paths, NULL) < 0)
13283 goto cleanup;
13285 if (qemuDomainNamespaceMknodPaths(vm, (const char **)paths, npaths) < 0)
13286 goto cleanup;
13288 ret = 0;
13289 cleanup:
13290 for (i = 0; i < npaths; i++)
13291 VIR_FREE(paths[i]);
13292 VIR_FREE(paths);
13293 return ret;
13298 qemuDomainNamespaceTeardownHostdev(virDomainObjPtr vm,
13299 virDomainHostdevDefPtr hostdev)
13301 int ret = -1;
13302 char **paths = NULL;
13303 size_t i, npaths = 0;
13305 if (qemuDomainGetHostdevPath(vm->def, hostdev, true,
13306 &npaths, &paths, NULL) < 0)
13307 goto cleanup;
13309 if (qemuDomainNamespaceUnlinkPaths(vm, (const char **)paths, npaths) < 0)
13310 goto cleanup;
13312 ret = 0;
13313 cleanup:
13314 for (i = 0; i < npaths; i++)
13315 VIR_FREE(paths[i]);
13316 VIR_FREE(paths);
13317 return ret;
13322 qemuDomainNamespaceSetupMemory(virDomainObjPtr vm,
13323 virDomainMemoryDefPtr mem)
13325 if (mem->model != VIR_DOMAIN_MEMORY_MODEL_NVDIMM)
13326 return 0;
13328 if (qemuDomainNamespaceMknodPath(vm, mem->nvdimmPath) < 0)
13329 return -1;
13331 return 0;
13336 qemuDomainNamespaceTeardownMemory(virDomainObjPtr vm,
13337 virDomainMemoryDefPtr mem)
13339 if (mem->model != VIR_DOMAIN_MEMORY_MODEL_NVDIMM)
13340 return 0;
13342 if (qemuDomainNamespaceUnlinkPath(vm, mem->nvdimmPath) < 0)
13343 return -1;
13345 return 0;
13350 qemuDomainNamespaceSetupChardev(virDomainObjPtr vm,
13351 virDomainChrDefPtr chr)
13353 const char *path;
13355 if (!(path = virDomainChrSourceDefGetPath(chr->source)))
13356 return 0;
13358 /* Socket created by qemu. It doesn't exist upfront. */
13359 if (chr->source->type == VIR_DOMAIN_CHR_TYPE_UNIX &&
13360 chr->source->data.nix.listen)
13361 return 0;
13363 if (qemuDomainNamespaceMknodPath(vm, path) < 0)
13364 return -1;
13366 return 0;
13371 qemuDomainNamespaceTeardownChardev(virDomainObjPtr vm,
13372 virDomainChrDefPtr chr)
13374 const char *path = NULL;
13376 if (chr->source->type != VIR_DOMAIN_CHR_TYPE_DEV)
13377 return 0;
13379 path = chr->source->data.file.path;
13381 if (qemuDomainNamespaceUnlinkPath(vm, path) < 0)
13382 return -1;
13384 return 0;
13389 qemuDomainNamespaceSetupRNG(virDomainObjPtr vm,
13390 virDomainRNGDefPtr rng)
13392 const char *path = NULL;
13394 switch ((virDomainRNGBackend) rng->backend) {
13395 case VIR_DOMAIN_RNG_BACKEND_RANDOM:
13396 path = rng->source.file;
13397 break;
13399 case VIR_DOMAIN_RNG_BACKEND_EGD:
13400 case VIR_DOMAIN_RNG_BACKEND_LAST:
13401 break;
13404 if (path && qemuDomainNamespaceMknodPath(vm, path) < 0)
13405 return -1;
13407 return 0;
13412 qemuDomainNamespaceTeardownRNG(virDomainObjPtr vm,
13413 virDomainRNGDefPtr rng)
13415 const char *path = NULL;
13417 switch ((virDomainRNGBackend) rng->backend) {
13418 case VIR_DOMAIN_RNG_BACKEND_RANDOM:
13419 path = rng->source.file;
13420 break;
13422 case VIR_DOMAIN_RNG_BACKEND_EGD:
13423 case VIR_DOMAIN_RNG_BACKEND_LAST:
13424 break;
13427 if (path && qemuDomainNamespaceUnlinkPath(vm, path) < 0)
13428 return -1;
13430 return 0;
13435 qemuDomainNamespaceSetupInput(virDomainObjPtr vm,
13436 virDomainInputDefPtr input)
13438 const char *path = NULL;
13440 if (!(path = virDomainInputDefGetPath(input)))
13441 return 0;
13443 if (path && qemuDomainNamespaceMknodPath(vm, path) < 0)
13444 return -1;
13445 return 0;
13450 qemuDomainNamespaceTeardownInput(virDomainObjPtr vm,
13451 virDomainInputDefPtr input)
13453 const char *path = NULL;
13455 if (!(path = virDomainInputDefGetPath(input)))
13456 return 0;
13458 if (path && qemuDomainNamespaceUnlinkPath(vm, path) < 0)
13459 return -1;
13461 return 0;
13466 * qemuDomainDiskLookupByNodename:
13467 * @def: domain definition to look for the disk
13468 * @nodename: block backend node name to find
13469 * @src: filled with the specific backing store element if provided
13470 * @idx: index of @src in the backing chain, if provided
13472 * Looks up the disk in the domain via @nodename and returns its definition.
13473 * Optionally fills @src and @idx if provided with the specific backing chain
13474 * element which corresponds to the node name.
13476 virDomainDiskDefPtr
13477 qemuDomainDiskLookupByNodename(virDomainDefPtr def,
13478 const char *nodename,
13479 virStorageSourcePtr *src,
13480 unsigned int *idx)
13482 size_t i;
13483 unsigned int srcindex;
13484 virStorageSourcePtr tmp = NULL;
13486 if (!idx)
13487 idx = &srcindex;
13489 if (src)
13490 *src = NULL;
13492 *idx = 0;
13494 for (i = 0; i < def->ndisks; i++) {
13495 if ((tmp = virStorageSourceFindByNodeName(def->disks[i]->src,
13496 nodename, idx))) {
13497 if (src)
13498 *src = tmp;
13500 return def->disks[i];
13504 return NULL;
13509 * qemuDomainDiskBackingStoreGetName:
13511 * Creates a name using the indexed syntax (vda[1])for the given backing store
13512 * entry for a disk.
13514 char *
13515 qemuDomainDiskBackingStoreGetName(virDomainDiskDefPtr disk,
13516 virStorageSourcePtr src ATTRIBUTE_UNUSED,
13517 unsigned int idx)
13519 char *ret = NULL;
13521 if (idx)
13522 ignore_value(virAsprintf(&ret, "%s[%d]", disk->dst, idx));
13523 else
13524 ignore_value(VIR_STRDUP(ret, disk->dst));
13526 return ret;
13530 virStorageSourcePtr
13531 qemuDomainGetStorageSourceByDevstr(const char *devstr,
13532 virDomainDefPtr def)
13534 virDomainDiskDefPtr disk = NULL;
13535 virStorageSourcePtr src = NULL;
13536 char *target = NULL;
13537 unsigned int idx;
13538 size_t i;
13540 if (virStorageFileParseBackingStoreStr(devstr, &target, &idx) < 0) {
13541 virReportError(VIR_ERR_INVALID_ARG,
13542 _("failed to parse block device '%s'"), devstr);
13543 return NULL;
13546 for (i = 0; i < def->ndisks; i++) {
13547 if (STREQ(target, def->disks[i]->dst)) {
13548 disk = def->disks[i];
13549 break;
13553 if (!disk) {
13554 virReportError(VIR_ERR_INVALID_ARG,
13555 _("failed to find disk '%s'"), target);
13556 goto cleanup;
13559 if (idx == 0)
13560 src = disk->src;
13561 else
13562 src = virStorageFileChainLookup(disk->src, NULL, NULL, idx, NULL);
13564 cleanup:
13565 VIR_FREE(target);
13566 return src;
13570 static void
13571 qemuDomainSaveCookieDispose(void *obj)
13573 qemuDomainSaveCookiePtr cookie = obj;
13575 VIR_DEBUG("cookie=%p", cookie);
13577 virCPUDefFree(cookie->cpu);
13581 qemuDomainSaveCookiePtr
13582 qemuDomainSaveCookieNew(virDomainObjPtr vm ATTRIBUTE_UNUSED)
13584 qemuDomainObjPrivatePtr priv = vm->privateData;
13585 qemuDomainSaveCookiePtr cookie = NULL;
13587 if (qemuDomainInitialize() < 0)
13588 goto error;
13590 if (!(cookie = virObjectNew(qemuDomainSaveCookieClass)))
13591 goto error;
13593 if (priv->origCPU && !(cookie->cpu = virCPUDefCopy(vm->def->cpu)))
13594 goto error;
13596 VIR_DEBUG("Save cookie %p, cpu=%p", cookie, cookie->cpu);
13598 return cookie;
13600 error:
13601 virObjectUnref(cookie);
13602 return NULL;
13606 static int
13607 qemuDomainSaveCookieParse(xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
13608 virObjectPtr *obj)
13610 qemuDomainSaveCookiePtr cookie = NULL;
13612 if (qemuDomainInitialize() < 0)
13613 goto error;
13615 if (!(cookie = virObjectNew(qemuDomainSaveCookieClass)))
13616 goto error;
13618 if (virCPUDefParseXML(ctxt, "./cpu[1]", VIR_CPU_TYPE_GUEST,
13619 &cookie->cpu) < 0)
13620 goto error;
13622 *obj = (virObjectPtr) cookie;
13623 return 0;
13625 error:
13626 virObjectUnref(cookie);
13627 return -1;
13631 static int
13632 qemuDomainSaveCookieFormat(virBufferPtr buf,
13633 virObjectPtr obj)
13635 qemuDomainSaveCookiePtr cookie = (qemuDomainSaveCookiePtr) obj;
13637 if (cookie->cpu &&
13638 virCPUDefFormatBufFull(buf, cookie->cpu, NULL) < 0)
13639 return -1;
13641 return 0;
13645 virSaveCookieCallbacks virQEMUDriverDomainSaveCookie = {
13646 .parse = qemuDomainSaveCookieParse,
13647 .format = qemuDomainSaveCookieFormat,
13652 * qemuDomainUpdateCPU:
13653 * @vm: domain which is being started
13654 * @cpu: CPU updated when the domain was running previously (before migration,
13655 * snapshot, or save)
13656 * @origCPU: where to store the original CPU from vm->def in case @cpu was
13657 * used instead
13659 * Replace the CPU definition with the updated one when QEMU is new enough to
13660 * allow us to check extra features it is about to enable or disable when
13661 * starting a domain. The original CPU is stored in @origCPU.
13663 * Returns 0 on success, -1 on error.
13666 qemuDomainUpdateCPU(virDomainObjPtr vm,
13667 virCPUDefPtr cpu,
13668 virCPUDefPtr *origCPU)
13670 qemuDomainObjPrivatePtr priv = vm->privateData;
13672 *origCPU = NULL;
13674 if (!cpu || !vm->def->cpu ||
13675 !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_QUERY_CPU_MODEL_EXPANSION) ||
13676 virCPUDefIsEqual(vm->def->cpu, cpu, false))
13677 return 0;
13679 if (!(cpu = virCPUDefCopy(cpu)))
13680 return -1;
13682 VIR_DEBUG("Replacing CPU def with the updated one");
13684 *origCPU = vm->def->cpu;
13685 vm->def->cpu = cpu;
13687 return 0;
13692 * qemuDomainFixupCPUS:
13693 * @vm: domain object
13694 * @origCPU: original CPU used when the domain was started
13696 * Libvirt older than 3.9.0 could have messed up the expansion of host-model
13697 * CPU when reconnecting to a running domain by adding features QEMU does not
13698 * support (such as cmt). This API fixes both the actual CPU provided by QEMU
13699 * (stored in the domain object) and the @origCPU used when starting the
13700 * domain.
13702 * This is safe even if the original CPU definition used mode='custom' (rather
13703 * than host-model) since we know QEMU was able to start the domain and thus
13704 * the CPU definitions do not contain any features unknown to QEMU.
13706 * This function can only be used on an active domain or when restoring a
13707 * domain which was running.
13709 * Returns 0 on success, -1 on error.
13712 qemuDomainFixupCPUs(virDomainObjPtr vm,
13713 virCPUDefPtr *origCPU)
13715 virCPUDefPtr fixedCPU = NULL;
13716 virCPUDefPtr fixedOrig = NULL;
13717 virArch arch = vm->def->os.arch;
13718 int ret = -1;
13720 if (!ARCH_IS_X86(arch))
13721 return 0;
13723 if (!vm->def->cpu ||
13724 vm->def->cpu->mode != VIR_CPU_MODE_CUSTOM ||
13725 !vm->def->cpu->model)
13726 return 0;
13728 /* Missing origCPU means QEMU created exactly the same virtual CPU which
13729 * we asked for or libvirt was too old to mess up the translation from
13730 * host-model.
13732 if (!*origCPU)
13733 return 0;
13735 if (virCPUDefFindFeature(vm->def->cpu, "cmt") &&
13736 (!(fixedCPU = virCPUDefCopyWithoutModel(vm->def->cpu)) ||
13737 virCPUDefCopyModelFilter(fixedCPU, vm->def->cpu, false,
13738 virQEMUCapsCPUFilterFeatures, &arch) < 0))
13739 goto cleanup;
13741 if (virCPUDefFindFeature(*origCPU, "cmt") &&
13742 (!(fixedOrig = virCPUDefCopyWithoutModel(*origCPU)) ||
13743 virCPUDefCopyModelFilter(fixedOrig, *origCPU, false,
13744 virQEMUCapsCPUFilterFeatures, &arch) < 0))
13745 goto cleanup;
13747 if (fixedCPU) {
13748 virCPUDefFree(vm->def->cpu);
13749 VIR_STEAL_PTR(vm->def->cpu, fixedCPU);
13752 if (fixedOrig) {
13753 virCPUDefFree(*origCPU);
13754 VIR_STEAL_PTR(*origCPU, fixedOrig);
13757 ret = 0;
13759 cleanup:
13760 virCPUDefFree(fixedCPU);
13761 virCPUDefFree(fixedOrig);
13762 return ret;
13767 * qemuDomainUpdateQEMUCaps:
13768 * @vm: domain object
13769 * @qemuCapsCache: cache of QEMU capabilities
13771 * This function updates the used QEMU capabilities of @vm by querying
13772 * the QEMU capabilities cache.
13774 * Returns 0 on success, -1 on error.
13777 qemuDomainUpdateQEMUCaps(virDomainObjPtr vm,
13778 virFileCachePtr qemuCapsCache)
13780 qemuDomainObjPrivatePtr priv = vm->privateData;
13782 virObjectUnref(priv->qemuCaps);
13783 if (!(priv->qemuCaps = virQEMUCapsCacheLookupCopy(qemuCapsCache,
13784 vm->def->emulator,
13785 vm->def->os.machine)))
13786 return -1;
13787 return 0;
13791 char *
13792 qemuDomainGetMachineName(virDomainObjPtr vm)
13794 qemuDomainObjPrivatePtr priv = vm->privateData;
13795 virQEMUDriverPtr driver = priv->driver;
13796 char *ret = NULL;
13798 if (vm->pid > 0) {
13799 ret = virSystemdGetMachineNameByPID(vm->pid);
13800 if (!ret)
13801 virResetLastError();
13804 if (!ret)
13805 ret = virDomainGenerateMachineName("qemu", vm->def->id, vm->def->name,
13806 virQEMUDriverIsPrivileged(driver));
13808 return ret;
13812 /* Check whether the device address is using either 'ccw' or default s390
13813 * address format and whether that's "legal" for the current qemu and/or
13814 * guest os.machine type. This is the corollary to the code which doesn't
13815 * find the address type set using an emulator that supports either 'ccw'
13816 * or s390 and sets the address type based on the capabilities.
13818 * If the address is using 'ccw' or s390 and it's not supported, generate
13819 * an error and return false; otherwise, return true.
13821 bool
13822 qemuDomainCheckCCWS390AddressSupport(const virDomainDef *def,
13823 const virDomainDeviceInfo *info,
13824 virQEMUCapsPtr qemuCaps,
13825 const char *devicename)
13827 if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
13828 if (!qemuDomainIsS390CCW(def)) {
13829 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13830 _("cannot use CCW address type for device "
13831 "'%s' using machine type '%s'"),
13832 devicename, def->os.machine);
13833 return false;
13834 } else if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCW)) {
13835 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
13836 _("CCW address type is not supported by "
13837 "this QEMU"));
13838 return false;
13840 } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390) {
13841 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_S390)) {
13842 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
13843 _("virtio S390 address type is not supported by "
13844 "this QEMU"));
13845 return false;
13848 return true;
13853 * qemuDomainPrepareDiskSourceData:
13855 * @disk: Disk config object
13856 * @src: source to start from
13857 * @cfg: qemu driver config object
13859 * Prepares various aspects of a storage source belonging to a disk backing
13860 * chain. This function should be also called for detected backing chain
13861 * members.
13864 qemuDomainPrepareDiskSourceData(virDomainDiskDefPtr disk,
13865 virStorageSourcePtr src,
13866 virQEMUDriverConfigPtr cfg,
13867 virQEMUCapsPtr qemuCaps)
13869 /* transfer properties valid only for the top level image */
13870 if (src == disk->src)
13871 src->detect_zeroes = disk->detect_zeroes;
13873 if (cfg &&
13874 src->type == VIR_STORAGE_TYPE_NETWORK &&
13875 src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER &&
13876 virQEMUCapsGet(qemuCaps, QEMU_CAPS_GLUSTER_DEBUG_LEVEL)) {
13877 src->debug = true;
13878 src->debugLevel = cfg->glusterDebugLevel;
13881 /* transfer properties valid for the full chain */
13882 src->iomode = disk->iomode;
13883 src->cachemode = disk->cachemode;
13884 src->discard = disk->discard;
13886 if (disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
13887 src->floppyimg = true;
13889 return 0;
13893 static void
13894 qemuDomainPrepareDiskCachemode(virDomainDiskDefPtr disk)
13896 if (disk->cachemode == VIR_DOMAIN_DISK_CACHE_DEFAULT &&
13897 disk->src->shared && !disk->src->readonly)
13898 disk->cachemode = VIR_DOMAIN_DISK_CACHE_DISABLE;
13902 static int
13903 qemuDomainPrepareStorageSourcePR(virStorageSourcePtr src,
13904 qemuDomainObjPrivatePtr priv,
13905 const char *parentalias)
13907 if (!src->pr)
13908 return 0;
13910 if (virStoragePRDefIsManaged(src->pr)) {
13911 VIR_FREE(src->pr->path);
13912 if (!(src->pr->path = qemuDomainGetManagedPRSocketPath(priv)))
13913 return -1;
13914 if (VIR_STRDUP(src->pr->mgralias, qemuDomainGetManagedPRAlias()) < 0)
13915 return -1;
13916 } else {
13917 if (!(src->pr->mgralias = qemuDomainGetUnmanagedPRAlias(parentalias)))
13918 return -1;
13921 return 0;
13926 * qemuDomainPrepareDiskSourceLegacy:
13927 * @disk: disk to prepare
13928 * @priv: VM private data
13929 * @cfg: qemu driver config
13931 * Prepare any disk source relevant data for use with the -drive command line.
13933 static int
13934 qemuDomainPrepareDiskSourceLegacy(virDomainDiskDefPtr disk,
13935 qemuDomainObjPrivatePtr priv,
13936 virQEMUDriverConfigPtr cfg)
13938 if (qemuDomainValidateStorageSource(disk->src, priv->qemuCaps) < 0)
13939 return -1;
13941 if (qemuDomainPrepareDiskSourceData(disk, disk->src, cfg, priv->qemuCaps) < 0)
13942 return -1;
13944 if (qemuDomainSecretStorageSourcePrepare(priv, disk->src,
13945 disk->info.alias,
13946 disk->info.alias) < 0)
13947 return -1;
13949 if (qemuDomainPrepareStorageSourcePR(disk->src, priv, disk->info.alias) < 0)
13950 return -1;
13952 if (qemuDomainPrepareStorageSourceTLS(disk->src, cfg, disk->info.alias,
13953 priv->qemuCaps) < 0)
13954 return -1;
13956 return 0;
13960 static int
13961 qemuDomainPrepareStorageSourceBlockdev(virDomainDiskDefPtr disk,
13962 virStorageSourcePtr src,
13963 qemuDomainObjPrivatePtr priv,
13964 virQEMUDriverConfigPtr cfg)
13966 src->id = qemuDomainStorageIdNew(priv);
13968 if (virAsprintf(&src->nodestorage, "libvirt-%u-storage", src->id) < 0 ||
13969 virAsprintf(&src->nodeformat, "libvirt-%u-format", src->id) < 0)
13970 return -1;
13972 if (qemuDomainValidateStorageSource(src, priv->qemuCaps) < 0)
13973 return -1;
13975 if (qemuDomainPrepareDiskSourceData(disk, src, cfg, priv->qemuCaps) < 0)
13976 return -1;
13978 if (qemuDomainSecretStorageSourcePrepare(priv, src,
13979 src->nodestorage,
13980 src->nodeformat) < 0)
13981 return -1;
13983 if (qemuDomainPrepareStorageSourcePR(src, priv, src->nodestorage) < 0)
13984 return -1;
13986 if (qemuDomainPrepareStorageSourceTLS(src, cfg, src->nodestorage,
13987 priv->qemuCaps) < 0)
13988 return -1;
13990 return 0;
13994 static int
13995 qemuDomainPrepareDiskSourceBlockdev(virDomainDiskDefPtr disk,
13996 qemuDomainObjPrivatePtr priv,
13997 virQEMUDriverConfigPtr cfg)
13999 qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
14000 virStorageSourcePtr n;
14002 if (disk->copy_on_read == VIR_TRISTATE_SWITCH_ON &&
14003 !diskPriv->nodeCopyOnRead &&
14004 virAsprintf(&diskPriv->nodeCopyOnRead, "libvirt-CoR-%s", disk->dst) < 0)
14005 return -1;
14007 for (n = disk->src; virStorageSourceIsBacking(n); n = n->backingStore) {
14008 if (qemuDomainPrepareStorageSourceBlockdev(disk, n, priv, cfg) < 0)
14009 return -1;
14012 return 0;
14017 qemuDomainPrepareDiskSource(virDomainDiskDefPtr disk,
14018 qemuDomainObjPrivatePtr priv,
14019 virQEMUDriverConfigPtr cfg)
14021 qemuDomainPrepareDiskCachemode(disk);
14023 /* add raw file format if the storage pool did not fill it in */
14024 if (disk->src->type == VIR_STORAGE_TYPE_VOLUME &&
14025 disk->src->format <= VIR_STORAGE_FILE_NONE)
14026 disk->src->format = VIR_STORAGE_FILE_RAW;
14028 if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV)) {
14029 if (qemuDomainPrepareDiskSourceBlockdev(disk, priv, cfg) < 0)
14030 return -1;
14031 } else {
14032 if (qemuDomainPrepareDiskSourceLegacy(disk, priv, cfg) < 0)
14033 return -1;
14036 return 0;
14041 * qemuDomainDiskCachemodeFlags:
14043 * Converts disk cachemode to the cache mode options for qemu. Returns -1 for
14044 * invalid @cachemode values and fills the flags and returns 0 on success.
14045 * Flags may be NULL.
14048 qemuDomainDiskCachemodeFlags(int cachemode,
14049 bool *writeback,
14050 bool *direct,
14051 bool *noflush)
14053 bool dummy;
14055 if (!writeback)
14056 writeback = &dummy;
14058 if (!direct)
14059 direct = &dummy;
14061 if (!noflush)
14062 noflush = &dummy;
14064 /* Mapping of cache modes to the attributes according to qemu-options.hx
14065 * │ cache.writeback cache.direct cache.no-flush
14066 * ─────────────┼─────────────────────────────────────────────────
14067 * writeback │ true false false
14068 * none │ true true false
14069 * writethrough │ false false false
14070 * directsync │ false true false
14071 * unsafe │ true false true
14073 switch ((virDomainDiskCache) cachemode) {
14074 case VIR_DOMAIN_DISK_CACHE_DISABLE: /* 'none' */
14075 *writeback = true;
14076 *direct = true;
14077 *noflush = false;
14078 break;
14080 case VIR_DOMAIN_DISK_CACHE_WRITETHRU:
14081 *writeback = false;
14082 *direct = false;
14083 *noflush = false;
14084 break;
14086 case VIR_DOMAIN_DISK_CACHE_WRITEBACK:
14087 *writeback = true;
14088 *direct = false;
14089 *noflush = false;
14090 break;
14092 case VIR_DOMAIN_DISK_CACHE_DIRECTSYNC:
14093 *writeback = false;
14094 *direct = true;
14095 *noflush = false;
14096 break;
14098 case VIR_DOMAIN_DISK_CACHE_UNSAFE:
14099 *writeback = true;
14100 *direct = false;
14101 *noflush = true;
14102 break;
14104 case VIR_DOMAIN_DISK_CACHE_DEFAULT:
14105 case VIR_DOMAIN_DISK_CACHE_LAST:
14106 default:
14107 virReportEnumRangeError(virDomainDiskCache, cachemode);
14108 return -1;
14111 return 0;
14115 void
14116 qemuProcessEventFree(struct qemuProcessEvent *event)
14118 if (!event)
14119 return;
14121 switch (event->eventType) {
14122 case QEMU_PROCESS_EVENT_GUESTPANIC:
14123 qemuMonitorEventPanicInfoFree(event->data);
14124 break;
14125 case QEMU_PROCESS_EVENT_RDMA_GID_STATUS_CHANGED:
14126 qemuMonitorEventRdmaGidStatusFree(event->data);
14127 break;
14128 case QEMU_PROCESS_EVENT_WATCHDOG:
14129 case QEMU_PROCESS_EVENT_DEVICE_DELETED:
14130 case QEMU_PROCESS_EVENT_NIC_RX_FILTER_CHANGED:
14131 case QEMU_PROCESS_EVENT_SERIAL_CHANGED:
14132 case QEMU_PROCESS_EVENT_BLOCK_JOB:
14133 case QEMU_PROCESS_EVENT_MONITOR_EOF:
14134 VIR_FREE(event->data);
14135 break;
14136 case QEMU_PROCESS_EVENT_PR_DISCONNECT:
14137 case QEMU_PROCESS_EVENT_LAST:
14138 break;
14140 VIR_FREE(event);
14144 char *
14145 qemuDomainGetManagedPRSocketPath(qemuDomainObjPrivatePtr priv)
14147 char *ret = NULL;
14149 ignore_value(virAsprintf(&ret, "%s/%s.sock", priv->libDir,
14150 qemuDomainGetManagedPRAlias()));
14152 return ret;
14157 * qemuDomainStorageIdNew:
14158 * @priv: qemu VM private data object.
14160 * Generate a new unique id for a storage object. Useful for node name generation.
14162 unsigned int
14163 qemuDomainStorageIdNew(qemuDomainObjPrivatePtr priv)
14165 return ++priv->nodenameindex;
14170 * qemuDomainStorageIdReset:
14171 * @priv: qemu VM private data object.
14173 * Resets the data for the node name generator. The node names need to be unique
14174 * for a single instance, so can be reset on VM shutdown.
14176 void
14177 qemuDomainStorageIdReset(qemuDomainObjPrivatePtr priv)
14179 priv->nodenameindex = 0;
14183 virDomainEventResumedDetailType
14184 qemuDomainRunningReasonToResumeEvent(virDomainRunningReason reason)
14186 switch (reason) {
14187 case VIR_DOMAIN_RUNNING_RESTORED:
14188 case VIR_DOMAIN_RUNNING_FROM_SNAPSHOT:
14189 return VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT;
14191 case VIR_DOMAIN_RUNNING_MIGRATED:
14192 case VIR_DOMAIN_RUNNING_MIGRATION_CANCELED:
14193 return VIR_DOMAIN_EVENT_RESUMED_MIGRATED;
14195 case VIR_DOMAIN_RUNNING_POSTCOPY:
14196 return VIR_DOMAIN_EVENT_RESUMED_POSTCOPY;
14198 case VIR_DOMAIN_RUNNING_UNKNOWN:
14199 case VIR_DOMAIN_RUNNING_SAVE_CANCELED:
14200 case VIR_DOMAIN_RUNNING_BOOTED:
14201 case VIR_DOMAIN_RUNNING_UNPAUSED:
14202 case VIR_DOMAIN_RUNNING_WAKEUP:
14203 case VIR_DOMAIN_RUNNING_CRASHED:
14204 case VIR_DOMAIN_RUNNING_LAST:
14205 break;
14208 return VIR_DOMAIN_EVENT_RESUMED_UNPAUSED;
14212 /* qemuDomainIsUsingNoShutdown:
14213 * @priv: Domain private data
14215 * If JSON monitor is enabled, we can receive an event when QEMU stops. If
14216 * we use no-shutdown, then we can watch for this event and do a soft/warm
14217 * reboot.
14219 * Returns: @true when -no-shutdown either should be or was added to the
14220 * command line.
14222 bool
14223 qemuDomainIsUsingNoShutdown(qemuDomainObjPrivatePtr priv)
14225 return priv->monJSON && priv->allowReboot == VIR_TRISTATE_BOOL_YES;
14229 bool
14230 qemuDomainDiskIsMissingLocalOptional(virDomainDiskDefPtr disk)
14232 return disk->startupPolicy == VIR_DOMAIN_STARTUP_POLICY_OPTIONAL &&
14233 virStorageSourceIsLocalStorage(disk->src) && disk->src->path &&
14234 !virFileExists(disk->src->path);
14239 qemuDomainNVRAMPathGenerate(virQEMUDriverConfigPtr cfg,
14240 virDomainDefPtr def)
14242 if (def->os.loader &&
14243 def->os.loader->type == VIR_DOMAIN_LOADER_TYPE_PFLASH &&
14244 def->os.loader->readonly == VIR_TRISTATE_SWITCH_ON &&
14245 !def->os.loader->nvram) {
14246 return virAsprintf(&def->os.loader->nvram, "%s/%s_VARS.fd",
14247 cfg->nvramDir, def->name);
14250 return 0;