1 /*
2  * cpu.c: internal functions for CPU manipulation
3  *
4  * Copyright (C) 2009-2013 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library.  If not, see
18  * <http://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 
23 #include "virlog.h"
24 #include "viralloc.h"
25 #include "virxml.h"
26 #include "cpu.h"
27 #include "cpu_map.h"
28 #include "cpu_x86.h"
29 #include "cpu_ppc64.h"
30 #include "cpu_s390.h"
31 #include "cpu_arm.h"
32 #include "capabilities.h"
33 #include "virstring.h"
34 
35 
36 #define VIR_FROM_THIS VIR_FROM_CPU
37 
38 VIR_LOG_INIT("cpu.cpu");
39 
40 static struct cpuArchDriver *drivers[] = {
41     &cpuDriverX86,
42     &cpuDriverPPC64,
43     &cpuDriverS390,
44     &cpuDriverArm,
45 };
46 
47 
48 static struct cpuArchDriver *
cpuGetSubDriver(virArch arch)49 cpuGetSubDriver(virArch arch)
50 {
51     size_t i;
52     size_t j;
53 
54     if (arch == VIR_ARCH_NONE) {
55         virReportError(VIR_ERR_INTERNAL_ERROR,
56                        "%s", _("undefined hardware architecture"));
57         return NULL;
58     }
59 
60     for (i = 0; i < G_N_ELEMENTS(drivers); i++) {
61         for (j = 0; j < drivers[i]->narch; j++) {
62             if (arch == drivers[i]->arch[j])
63                 return drivers[i];
64         }
65     }
66 
67     virReportError(VIR_ERR_NO_SUPPORT,
68                    _("'%s' architecture is not supported by CPU driver"),
69                    virArchToString(arch));
70     return NULL;
71 }
72 
73 
74 static struct cpuArchDriver *
cpuGetSubDriverByName(const char * name)75 cpuGetSubDriverByName(const char *name)
76 {
77     size_t i;
78 
79     for (i = 0; i < G_N_ELEMENTS(drivers); i++) {
80         if (STREQ_NULLABLE(name, drivers[i]->name))
81             return drivers[i];
82     }
83 
84     virReportError(VIR_ERR_INTERNAL_ERROR,
85                    _("CPU driver '%s' does not exist"),
86                    name);
87     return NULL;
88 }
89 
90 
91 /**
92  * virCPUCompareXML:
93  *
94  * @arch: CPU architecture
95  * @host: host CPU definition
96  * @xml: XML description of either guest or host CPU to be compared with @host
97  * @failIncompatible: return an error instead of VIR_CPU_COMPARE_INCOMPATIBLE
98  *
99  * Compares the CPU described by @xml with @host CPU.
100  *
101  * Returns VIR_CPU_COMPARE_ERROR on error, VIR_CPU_COMPARE_INCOMPATIBLE when
102  * the two CPUs are incompatible, VIR_CPU_COMPARE_IDENTICAL when the two CPUs
103  * are identical, VIR_CPU_COMPARE_SUPERSET when the @xml CPU is a superset of
104  * the @host CPU. If @failIncompatible is true, the function will return
105  * VIR_CPU_COMPARE_ERROR (and set VIR_ERR_CPU_INCOMPATIBLE error) when the
106  * two CPUs are incompatible.
107  */
108 virCPUCompareResult
virCPUCompareXML(virArch arch,virCPUDef * host,const char * xml,bool failIncompatible,bool validateXML)109 virCPUCompareXML(virArch arch,
110                  virCPUDef *host,
111                  const char *xml,
112                  bool failIncompatible,
113                  bool validateXML)
114 {
115     g_autoptr(virCPUDef) cpu = NULL;
116 
117     VIR_DEBUG("arch=%s, host=%p, xml=%s",
118               virArchToString(arch), host, NULLSTR(xml));
119 
120     if (virCPUDefParseXMLString(xml, VIR_CPU_TYPE_AUTO, &cpu, validateXML) < 0)
121         return VIR_CPU_COMPARE_ERROR;
122 
123     return virCPUCompare(arch, host, cpu, failIncompatible);
124 }
125 
126 
127 /**
128  * virCPUCompare:
129  *
130  * @arch: CPU architecture
131  * @host: host CPU definition
132  * @cpu: either guest or host CPU to be compared with @host
133  * @failIncompatible: return an error instead of VIR_CPU_COMPARE_INCOMPATIBLE
134  *
135  * Compares the CPU described by @cpu with @host CPU.
136  *
137  * Returns VIR_CPU_COMPARE_ERROR on error, VIR_CPU_COMPARE_INCOMPATIBLE when
138  * the two CPUs are incompatible, VIR_CPU_COMPARE_IDENTICAL when the two CPUs
139  * are identical, VIR_CPU_COMPARE_SUPERSET when the @cpu CPU is a superset of
140  * the @host CPU. If @failIncompatible is true, the function will return
141  * VIR_CPU_COMPARE_ERROR (and set VIR_ERR_CPU_INCOMPATIBLE error) when the
142  * two CPUs are incompatible.
143  */
144 virCPUCompareResult
virCPUCompare(virArch arch,virCPUDef * host,virCPUDef * cpu,bool failIncompatible)145 virCPUCompare(virArch arch,
146               virCPUDef *host,
147               virCPUDef *cpu,
148               bool failIncompatible)
149 {
150     struct cpuArchDriver *driver;
151 
152     VIR_DEBUG("arch=%s, host=%p, cpu=%p",
153               virArchToString(arch), host, cpu);
154 
155     if (!(driver = cpuGetSubDriver(arch)))
156         return VIR_CPU_COMPARE_ERROR;
157 
158     if (!driver->compare) {
159         virReportError(VIR_ERR_NO_SUPPORT,
160                        _("cannot compare CPUs of %s architecture"),
161                        virArchToString(arch));
162         return VIR_CPU_COMPARE_ERROR;
163     }
164 
165     return driver->compare(host, cpu, failIncompatible);
166 }
167 
168 
169 /**
170  * cpuDecode:
171  *
172  * @cpu: CPU definition stub to be filled in
173  * @data: internal CPU data to be decoded into @cpu definition
174  * @models: list of CPU models that can be considered when decoding @data
175  *
176  * Decodes internal CPU data into a CPU definition consisting of a CPU model
177  * and a list of CPU features. The @cpu model stub is supposed to have arch,
178  * type, match and fallback members set, this function will add the rest. If
179  * @models list is NULL, all models supported by libvirt will be considered
180  * when decoding the data. In general, this function will select the model
181  * closest to the CPU specified by @data.
182  *
183  * For VIR_ARCH_I686 and VIR_ARCH_X86_64 architectures this means the computed
184  * CPU definition will have the shortest possible list of additional features.
185  *
186  * Returns 0 on success, -1 on error.
187  */
188 int
cpuDecode(virCPUDef * cpu,const virCPUData * data,virDomainCapsCPUModels * models)189 cpuDecode(virCPUDef *cpu,
190           const virCPUData *data,
191           virDomainCapsCPUModels *models)
192 {
193     struct cpuArchDriver *driver;
194 
195     VIR_DEBUG("cpu=%p, data=%p, models=%p", cpu, data, models);
196     if (models) {
197         size_t i;
198         for (i = 0; i < models->nmodels; i++)
199             VIR_DEBUG("models[%zu]=%s", i, models->models[i].name);
200     }
201 
202     if (cpu->type > VIR_CPU_TYPE_GUEST ||
203         cpu->mode != VIR_CPU_MODE_CUSTOM) {
204         virReportError(VIR_ERR_INVALID_ARG, "%s",
205                        _("invalid CPU definition stub"));
206         return -1;
207     }
208 
209     if ((driver = cpuGetSubDriver(data->arch)) == NULL)
210         return -1;
211 
212     if (driver->decode == NULL) {
213         virReportError(VIR_ERR_NO_SUPPORT,
214                        _("cannot decode CPU data for %s architecture"),
215                        virArchToString(cpu->arch));
216         return -1;
217     }
218 
219     return driver->decode(cpu, data, models);
220 }
221 
222 
223 /**
224  * cpuEncode:
225  *
226  * @arch: CPU architecture
227  * @cpu: CPU definition to be encoded into internal CPU driver representation
228  * @forced: where to store CPU data corresponding to forced features
229  * @required: where to store CPU data corresponding to required features
230  * @optional: where to store CPU data corresponding to optional features
231  * @disabled: where to store CPU data corresponding to disabled features
232  * @forbidden: where to store CPU data corresponding to forbidden features
233  * @vendor: where to store CPU data corresponding to CPU vendor
234  *
235  * Encode CPU definition from @cpu into internal CPU driver representation.
236  * Any of @forced, @required, @optional, @disabled, @forbidden and @vendor
237  * arguments can be NULL in case the caller is not interested in the
238  * corresponding data.
239  *
240  * Returns 0 on success, -1 on error.
241  */
242 int
cpuEncode(virArch arch,const virCPUDef * cpu,virCPUData ** forced,virCPUData ** required,virCPUData ** optional,virCPUData ** disabled,virCPUData ** forbidden,virCPUData ** vendor)243 cpuEncode(virArch arch,
244           const virCPUDef *cpu,
245           virCPUData **forced,
246           virCPUData **required,
247           virCPUData **optional,
248           virCPUData **disabled,
249           virCPUData **forbidden,
250           virCPUData **vendor)
251 {
252     struct cpuArchDriver *driver;
253 
254     VIR_DEBUG("arch=%s, cpu=%p, forced=%p, required=%p, "
255               "optional=%p, disabled=%p, forbidden=%p, vendor=%p",
256               virArchToString(arch), cpu, forced, required,
257               optional, disabled, forbidden, vendor);
258 
259     if (!cpu->model) {
260         virReportError(VIR_ERR_INVALID_ARG, "%s",
261                        _("no guest CPU model specified"));
262         return -1;
263     }
264 
265     if ((driver = cpuGetSubDriver(arch)) == NULL)
266         return -1;
267 
268     if (driver->encode == NULL) {
269         virReportError(VIR_ERR_NO_SUPPORT,
270                        _("cannot encode CPU data for %s architecture"),
271                        virArchToString(arch));
272         return -1;
273     }
274 
275     return driver->encode(arch, cpu, forced, required,
276                           optional, disabled, forbidden, vendor);
277 }
278 
279 
280 /**
281  * virCPUDataNew:
282  *
283  * Returns an allocated memory for virCPUData or NULL on error.
284  */
285 virCPUData *
virCPUDataNew(virArch arch)286 virCPUDataNew(virArch arch)
287 {
288     virCPUData *data;
289 
290     data = g_new0(virCPUData, 1);
291     data->arch = arch;
292 
293     return data;
294 }
295 
296 
297 /**
298  * virCPUDataNewCopy:
299  *
300  * Returns a copy of @data or NULL on error.
301  */
302 virCPUData *
virCPUDataNewCopy(virCPUData * data)303 virCPUDataNewCopy(virCPUData *data)
304 {
305     struct cpuArchDriver *driver;
306 
307     VIR_DEBUG("data=%p", data);
308 
309     if (!data)
310         return NULL;
311 
312     if ((driver = cpuGetSubDriver(data->arch)) && driver->dataCopyNew)
313         return driver->dataCopyNew(data);
314 
315     return NULL;
316 }
317 
318 /**
319  * virCPUDataFree:
320  *
321  * @data: CPU data structure to be freed
322  *
323  * Free internal CPU data.
324  *
325  * Returns nothing.
326  */
327 void
virCPUDataFree(virCPUData * data)328 virCPUDataFree(virCPUData *data)
329 {
330     struct cpuArchDriver *driver;
331 
332     VIR_DEBUG("data=%p", data);
333 
334     if (!data)
335         return;
336 
337     if ((driver = cpuGetSubDriver(data->arch)) && driver->dataFree)
338         driver->dataFree(data);
339     else
340         g_free(data);
341 }
342 
343 
344 /**
345  * virCPUGetHostIsSupported:
346  *
347  * @arch: CPU architecture
348  *
349  * Check whether virCPUGetHost is supported for @arch.
350  *
351  * Returns true if virCPUGetHost is supported, false otherwise.
352  */
353 bool
virCPUGetHostIsSupported(virArch arch)354 virCPUGetHostIsSupported(virArch arch)
355 {
356     struct cpuArchDriver *driver;
357 
358     VIR_DEBUG("arch=%s", virArchToString(arch));
359 
360     return (driver = cpuGetSubDriver(arch)) && driver->getHost;
361 }
362 
363 
364 /**
365  * virCPUGetHost:
366  *
367  * @arch: CPU architecture
368  * @type: requested type of the CPU
369  * @nodeInfo: simplified CPU topology (optional)
370  * @models: list of CPU models that can be considered for host CPU
371  *
372  * Create CPU definition describing the host's CPU.
373  *
374  * The @type (either VIR_CPU_TYPE_HOST or VIR_CPU_TYPE_GUEST) specifies what
375  * type of CPU definition should be created. Specifically, VIR_CPU_TYPE_HOST
376  * CPUs may contain only features without any policy attribute. Requesting
377  * VIR_CPU_TYPE_GUEST provides better results because the CPU is allowed to
378  * contain disabled features.
379  *
380  * If @nodeInfo is not NULL (which is only allowed for VIR_CPU_TYPE_HOST CPUs),
381  * the CPU definition will have topology (sockets, cores, threads) filled in
382  * according to the content of @nodeInfo. The function fails only if @nodeInfo
383  * was not passed in and the assigned CPU driver was not able to detect the
384  * host CPU model. In other words, a CPU definition containing just the
385  * topology is a successful result even if detecting the host CPU model fails.
386  *
387  * It possible to limit the CPU model which may appear in the created CPU
388  * definition by passing non-NULL @models list. This is useful when requesting
389  * a CPU model usable on a specific hypervisor. If @models is NULL, any CPU
390  * model known to libvirt may appear in the result.
391  *
392  * Returns host CPU definition or NULL on error.
393  */
394 virCPUDef *
virCPUGetHost(virArch arch,virCPUType type,virNodeInfoPtr nodeInfo,virDomainCapsCPUModels * models)395 virCPUGetHost(virArch arch,
396               virCPUType type,
397               virNodeInfoPtr nodeInfo,
398               virDomainCapsCPUModels *models)
399 {
400     struct cpuArchDriver *driver;
401     g_autoptr(virCPUDef) cpu = NULL;
402 
403     VIR_DEBUG("arch=%s, type=%s, nodeInfo=%p, models=%p",
404               virArchToString(arch), virCPUTypeToString(type), nodeInfo,
405               models);
406 
407     if (!(driver = cpuGetSubDriver(arch)))
408         return NULL;
409 
410     cpu = virCPUDefNew();
411 
412     switch (type) {
413     case VIR_CPU_TYPE_HOST:
414         cpu->arch = arch;
415         cpu->type = type;
416         break;
417 
418     case VIR_CPU_TYPE_GUEST:
419         if (nodeInfo) {
420             virReportError(VIR_ERR_INVALID_ARG,
421                            _("cannot set topology for CPU type '%s'"),
422                            virCPUTypeToString(type));
423             return NULL;
424         }
425         cpu->type = type;
426         break;
427 
428     case VIR_CPU_TYPE_AUTO:
429     case VIR_CPU_TYPE_LAST:
430         virReportError(VIR_ERR_INVALID_ARG,
431                        _("unsupported CPU type: %s"),
432                        virCPUTypeToString(type));
433         return NULL;
434     }
435 
436     if (nodeInfo) {
437         cpu->sockets = nodeInfo->sockets;
438         cpu->dies = 1;
439         cpu->cores = nodeInfo->cores;
440         cpu->threads = nodeInfo->threads;
441     }
442 
443     /* Try to get the host CPU model, but don't really fail if nodeInfo is
444      * filled in.
445      */
446     if (driver->getHost) {
447         if (driver->getHost(cpu, models) < 0 && !nodeInfo)
448             return NULL;
449     } else if (nodeInfo) {
450         VIR_DEBUG("cannot detect host CPU model for %s architecture",
451                   virArchToString(arch));
452     } else {
453         virReportError(VIR_ERR_NO_SUPPORT,
454                        _("cannot detect host CPU model for %s architecture"),
455                        virArchToString(arch));
456         return NULL;
457     }
458 
459     return g_steal_pointer(&cpu);
460 }
461 
462 
463 virCPUDef *
virCPUProbeHost(virArch arch)464 virCPUProbeHost(virArch arch)
465 {
466     virNodeInfo nodeinfo;
467 
468     if (virCapabilitiesGetNodeInfo(&nodeinfo) < 0)
469         return NULL;
470 
471     return virCPUGetHost(arch, VIR_CPU_TYPE_HOST, &nodeinfo, NULL);
472 }
473 
474 
475 /**
476  * virCPUBaseline:
477  *
478  * @arch: CPU architecture, use VIR_ARCH_NONE to autodetect from @cpus
479  * @cpus: list of host CPU definitions
480  * @ncpus: number of CPUs in @cpus
481  * @models: list of CPU models that can be considered for the baseline CPU
482  * @features: optional NULL terminated list of allowed features
483  * @migratable: requests non-migratable features to be removed from the result
484  *
485  * Computes the most feature-rich CPU which is compatible with all given
486  * CPUs. If @models is NULL, all models supported by libvirt will
487  * be considered when computing the baseline CPU model, otherwise the baseline
488  * CPU model will be one of the provided CPU @models.
489  *
490  * Returns baseline CPU definition or NULL on error.
491  */
492 virCPUDef *
virCPUBaseline(virArch arch,virCPUDef ** cpus,unsigned int ncpus,virDomainCapsCPUModels * models,const char ** features,bool migratable)493 virCPUBaseline(virArch arch,
494                virCPUDef **cpus,
495                unsigned int ncpus,
496                virDomainCapsCPUModels *models,
497                const char **features,
498                bool migratable)
499 {
500     struct cpuArchDriver *driver;
501     size_t i;
502 
503     VIR_DEBUG("arch=%s, ncpus=%u, models=%p, features=%p, migratable=%d",
504               virArchToString(arch), ncpus, models, features, migratable);
505     if (cpus) {
506         for (i = 0; i < ncpus; i++)
507             VIR_DEBUG("cpus[%zu]=%p", i, cpus[i]);
508     }
509     if (models) {
510         for (i = 0; i < models->nmodels; i++)
511             VIR_DEBUG("models[%zu]=%s", i, models->models[i].name);
512     }
513 
514     if (!cpus && ncpus != 0) {
515         virReportError(VIR_ERR_INTERNAL_ERROR,
516                        "%s", _("nonzero ncpus doesn't match with NULL cpus"));
517         return NULL;
518     }
519 
520     if (ncpus < 1) {
521         virReportError(VIR_ERR_INVALID_ARG, "%s", _("no CPUs given"));
522         return NULL;
523     }
524 
525     for (i = 0; i < ncpus; i++) {
526         if (!cpus[i]) {
527             virReportError(VIR_ERR_INVALID_ARG,
528                            _("invalid CPU definition at index %zu"), i);
529             return NULL;
530         }
531         if (!cpus[i]->model) {
532             virReportError(VIR_ERR_INVALID_ARG,
533                            _("no CPU model specified at index %zu"), i);
534             return NULL;
535         }
536     }
537 
538     if (arch == VIR_ARCH_NONE)
539         arch = cpus[0]->arch;
540 
541     if (!(driver = cpuGetSubDriver(arch)))
542         return NULL;
543 
544     if (!driver->baseline) {
545         virReportError(VIR_ERR_NO_SUPPORT,
546                        _("cannot compute baseline CPU of %s architecture"),
547                        virArchToString(arch));
548         return NULL;
549     }
550 
551     return driver->baseline(cpus, ncpus, models, features, migratable);
552 }
553 
554 
555 /**
556  * virCPUUpdate:
557  *
558  * @arch: CPU architecture
559  * @guest: guest CPU definition to be updated
560  * @host: host CPU definition
561  *
562  * Updates @guest CPU definition possibly taking @host CPU into account. This
563  * is required for maintaining compatibility with older libvirt releases or to
564  * support guest CPU definitions specified relatively to host CPU, such as CPUs
565  * with VIR_CPU_MODE_CUSTOM and optional features or VIR_CPU_MATCH_MINIMUM, or
566  * CPUs with VIR_CPU_MODE_HOST_MODEL.
567  *
568  * Returns 0 on success, -1 on error.
569  */
570 int
virCPUUpdate(virArch arch,virCPUDef * guest,const virCPUDef * host)571 virCPUUpdate(virArch arch,
572              virCPUDef *guest,
573              const virCPUDef *host)
574 {
575     struct cpuArchDriver *driver;
576     bool relative;
577 
578     VIR_DEBUG("arch=%s, guest=%p mode=%s model=%s, host=%p model=%s",
579               virArchToString(arch), guest, virCPUModeTypeToString(guest->mode),
580               NULLSTR(guest->model), host, NULLSTR(host ? host->model : NULL));
581 
582     if (!(driver = cpuGetSubDriver(arch)))
583         return -1;
584 
585     switch ((virCPUMode) guest->mode) {
586     case VIR_CPU_MODE_HOST_PASSTHROUGH:
587     case VIR_CPU_MODE_MAXIMUM:
588         return 0;
589 
590     case VIR_CPU_MODE_HOST_MODEL:
591         relative = true;
592         break;
593 
594     case VIR_CPU_MODE_CUSTOM:
595         if (guest->match == VIR_CPU_MATCH_MINIMUM) {
596             relative = true;
597         } else {
598             size_t i;
599 
600             relative = false;
601             for (i = 0; i < guest->nfeatures; i++) {
602                 if (guest->features[i].policy == VIR_CPU_FEATURE_OPTIONAL) {
603                     relative = true;
604                     break;
605                 }
606             }
607         }
608         break;
609 
610     case VIR_CPU_MODE_LAST:
611     default:
612         virReportEnumRangeError(virCPUMode, guest->mode);
613         return -1;
614     }
615 
616     if (!driver->update) {
617         virReportError(VIR_ERR_NO_SUPPORT,
618                        _("cannot update guest CPU for %s architecture"),
619                        virArchToString(arch));
620         return -1;
621     }
622 
623     if (driver->update(guest, host, relative) < 0)
624         return -1;
625 
626     VIR_DEBUG("model=%s", NULLSTR(guest->model));
627     return 0;
628 }
629 
630 
631 /**
632  * virCPUUpdateLive:
633  *
634  * @arch: CPU architecture
635  * @cpu: guest CPU definition to be updated
636  * @dataEnabled: CPU data of the virtual CPU
637  * @dataDisabled: CPU data with features requested by @cpu but disabled by the
638  *                hypervisor
639  *
640  * Update custom mode CPU according to the virtual CPU created by the
641  * hypervisor. The function refuses to update the CPU in case cpu->check is set
642  * to VIR_CPU_CHECK_FULL.
643  *
644  * Returns -1 on error,
645  *          0 when the CPU was successfully updated,
646  *          1 when the operation does not make sense on the CPU or it is not
647  *            supported for the given architecture.
648  */
649 int
virCPUUpdateLive(virArch arch,virCPUDef * cpu,virCPUData * dataEnabled,virCPUData * dataDisabled)650 virCPUUpdateLive(virArch arch,
651                  virCPUDef *cpu,
652                  virCPUData *dataEnabled,
653                  virCPUData *dataDisabled)
654 {
655     struct cpuArchDriver *driver;
656 
657     VIR_DEBUG("arch=%s, cpu=%p, dataEnabled=%p, dataDisabled=%p",
658               virArchToString(arch), cpu, dataEnabled, dataDisabled);
659 
660     if (!(driver = cpuGetSubDriver(arch)))
661         return -1;
662 
663     if (!driver->updateLive)
664         return 1;
665 
666     if (cpu->mode == VIR_CPU_MODE_CUSTOM ||
667         cpu->check == VIR_CPU_CHECK_FULL) {
668         if (driver->updateLive(cpu, dataEnabled, dataDisabled) < 0)
669             return -1;
670 
671         return 0;
672     }
673 
674     return 1;
675 }
676 
677 
678 /**
679  * virCPUCheckFeature:
680  *
681  * @arch: CPU architecture
682  * @cpu: CPU definition
683  * @feature: feature to be checked for
684  *
685  * Checks whether @feature is supported by the CPU described by @cpu.
686  *
687  * Returns 1 if the feature is supported, 0 if it's not supported, or
688  * -1 on error.
689  */
690 int
virCPUCheckFeature(virArch arch,const virCPUDef * cpu,const char * feature)691 virCPUCheckFeature(virArch arch,
692                    const virCPUDef *cpu,
693                    const char *feature)
694 {
695     struct cpuArchDriver *driver;
696 
697     VIR_DEBUG("arch=%s, cpu=%p, feature=%s",
698               virArchToString(arch), cpu, feature);
699 
700     if (!(driver = cpuGetSubDriver(arch)))
701         return -1;
702 
703     if (!driver->checkFeature) {
704         virReportError(VIR_ERR_NO_SUPPORT,
705                        _("cannot check guest CPU feature for %s architecture"),
706                        virArchToString(arch));
707         return -1;
708     }
709 
710     return driver->checkFeature(cpu, feature);
711 }
712 
713 
714 /**
715  * virCPUCheckForbiddenFeatures:
716  *
717  * @guest: CPU definition
718  * @host: CPU definition
719  *
720  * Checks that @host enables no feature explicitly disabled by @guest.
721  *
722  * Returns 0 on success or -1 on error.
723  */
724 int
virCPUCheckForbiddenFeatures(virCPUDef * guest,const virCPUDef * host)725 virCPUCheckForbiddenFeatures(virCPUDef *guest, const virCPUDef *host)
726 {
727     size_t i;
728     for (i = 0; i < guest->nfeatures; ++i) {
729         virCPUFeatureDef *feature;
730 
731         if (guest->features[i].policy != VIR_CPU_FEATURE_FORBID)
732             continue;
733 
734         feature = virCPUDefFindFeature(host, guest->features[i].name);
735         if (!feature)
736             continue;
737 
738         if (feature->policy == VIR_CPU_FEATURE_DISABLE)
739             continue;
740 
741         virReportError(VIR_ERR_CPU_INCOMPATIBLE,
742                        _("Host CPU provides forbidden feature '%s'"),
743                        guest->features[i].name);
744         return -1;
745     }
746 
747     return 0;
748 }
749 
750 
751 /**
752  * virCPUDataCheckFeature:
753  *
754  * @data: CPU data
755  * @feature: feature to be checked for
756  *
757  * Checks whether @feature is supported by the CPU described by @data.
758  *
759  * Returns 1 if the feature is supported, 0 if it's not supported, or
760  * -1 on error.
761  */
762 int
virCPUDataCheckFeature(const virCPUData * data,const char * feature)763 virCPUDataCheckFeature(const virCPUData *data,
764                        const char *feature)
765 {
766     struct cpuArchDriver *driver;
767 
768     VIR_DEBUG("arch=%s, data=%p, feature=%s",
769               virArchToString(data->arch), data, feature);
770 
771     if (!(driver = cpuGetSubDriver(data->arch)))
772         return -1;
773 
774     if (!driver->dataCheckFeature) {
775         virReportError(VIR_ERR_NO_SUPPORT,
776                        _("cannot check guest CPU feature for %s architecture"),
777                        virArchToString(data->arch));
778         return -1;
779     }
780 
781     return driver->dataCheckFeature(data, feature);
782 }
783 
784 
785 /**
786  * virCPUDataFormat:
787  *
788  * @data: internal CPU representation
789  *
790  * Formats @data into XML for test purposes.
791  *
792  * Returns string representation of the XML describing @data or NULL on error.
793  */
794 char *
virCPUDataFormat(const virCPUData * data)795 virCPUDataFormat(const virCPUData *data)
796 {
797     struct cpuArchDriver *driver;
798 
799     VIR_DEBUG("data=%p", data);
800 
801     if (!(driver = cpuGetSubDriver(data->arch)))
802         return NULL;
803 
804     if (!driver->dataFormat) {
805         virReportError(VIR_ERR_NO_SUPPORT,
806                        _("cannot format %s CPU data"),
807                        virArchToString(data->arch));
808         return NULL;
809     }
810 
811     return driver->dataFormat(data);
812 }
813 
814 
815 /**
816  * virCPUDataParse:
817  *
818  * @xmlStr: XML string produced by virCPUDataFormat
819  *
820  * Parses XML representation of virCPUData structure for test purposes.
821  *
822  * Returns internal CPU data structure parsed from the XML or NULL on error.
823  */
824 virCPUData *
virCPUDataParse(const char * xmlStr)825 virCPUDataParse(const char *xmlStr)
826 {
827     g_autoptr(xmlDoc) xml = NULL;
828     g_autoptr(xmlXPathContext) ctxt = NULL;
829 
830     VIR_DEBUG("xmlStr=%s", xmlStr);
831 
832     if (!(xml = virXMLParseStringCtxt(xmlStr, _("CPU data"), &ctxt))) {
833         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
834                        _("cannot parse CPU data"));
835         return NULL;
836     }
837 
838     return virCPUDataParseNode(ctxt->node);
839 }
840 
841 
842 /**
843  * virCPUDataParseNode:
844  *
845  * @node: XML node as produced by virCPUDataFormat
846  *
847  * Parses XML representation of virCPUData structure.
848  *
849  * Returns internal CPU data structure parsed from the XML or NULL on error.
850  */
virCPUDataParseNode(xmlNodePtr node)851 virCPUData *virCPUDataParseNode(xmlNodePtr node)
852 {
853     g_autofree char *arch = NULL;
854     struct cpuArchDriver *driver;
855 
856     if (!(arch = virXMLPropString(node, "arch"))) {
857         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
858                        _("missing CPU data architecture"));
859         return NULL;
860     }
861 
862     if (!(driver = cpuGetSubDriverByName(arch)))
863         return NULL;
864 
865     if (!driver->dataParse) {
866         virReportError(VIR_ERR_NO_SUPPORT, _("cannot parse %s CPU data"), arch);
867         return NULL;
868     }
869 
870     return driver->dataParse(node);
871 }
872 
873 
874 /** virCPUModelIsAllowed:
875  *
876  * @model: CPU model to be checked
877  * @models: list of supported CPU models
878  *
879  * Checks whether @model can be found in the list of supported @models.
880  * If @models is NULL, all models are supported.
881  *
882  * Returns true if @model is supported, false otherwise.
883  */
884 bool
virCPUModelIsAllowed(const char * model,virDomainCapsCPUModels * models)885 virCPUModelIsAllowed(const char *model,
886                      virDomainCapsCPUModels *models)
887 {
888     if (!models)
889         return true;
890 
891     return !!virDomainCapsCPUModelsGet(models, model);
892 }
893 
894 
895 /**
896  * virCPUGetModels:
897  *
898  * @arch: CPU architecture
899  * @models: where to store the NULL-terminated list of supported models
900  *
901  * Fetches all CPU models supported by libvirt on @archName. If there are
902  * no restrictions on CPU models on @archName (i.e., the CPU model is just
903  * passed directly to a hypervisor), this function returns 0 and sets
904  * @models to NULL.
905  *
906  * Returns number of supported CPU models, 0 if any CPU model is supported,
907  * or -1 on error.
908  */
909 int
virCPUGetModels(virArch arch,char *** models)910 virCPUGetModels(virArch arch, char ***models)
911 {
912     struct cpuArchDriver *driver;
913 
914     VIR_DEBUG("arch=%s", virArchToString(arch));
915 
916     if (!(driver = cpuGetSubDriver(arch)))
917         return -1;
918 
919     if (!driver->getModels) {
920         if (models)
921             *models = NULL;
922         return 0;
923     }
924 
925     return driver->getModels(models);
926 }
927 
928 
929 /**
930  * virCPUTranslate:
931  *
932  * @arch: CPU architecture
933  * @cpu: CPU definition to be translated
934  * @models: list of allowed CPU models (NULL if all are allowed)
935  *
936  * Translates @cpu model (if allowed by @cpu->fallback) to a closest CPU model
937  * from @models list.
938  *
939  * The function does nothing (and returns 0) if @cpu does not have to be
940  * translated.
941  *
942  * Returns -1 on error, 0 on success.
943  */
944 int
virCPUTranslate(virArch arch,virCPUDef * cpu,virDomainCapsCPUModels * models)945 virCPUTranslate(virArch arch,
946                 virCPUDef *cpu,
947                 virDomainCapsCPUModels *models)
948 {
949     struct cpuArchDriver *driver;
950 
951     VIR_DEBUG("arch=%s, cpu=%p, model=%s, models=%p",
952               virArchToString(arch), cpu, NULLSTR(cpu->model), models);
953 
954     if (!(driver = cpuGetSubDriver(arch)))
955         return -1;
956 
957     if (cpu->mode == VIR_CPU_MODE_HOST_MODEL ||
958         cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH ||
959         cpu->mode == VIR_CPU_MODE_MAXIMUM)
960         return 0;
961 
962     if (virCPUModelIsAllowed(cpu->model, models))
963         return 0;
964 
965     if (cpu->fallback != VIR_CPU_FALLBACK_ALLOW) {
966         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
967                        _("CPU model %s is not supported by hypervisor"),
968                        cpu->model);
969         return -1;
970     }
971 
972     if (!driver->translate) {
973         virReportError(VIR_ERR_NO_SUPPORT,
974                        _("cannot translate CPU model %s to a supported model"),
975                        cpu->model);
976         return -1;
977     }
978 
979     if (driver->translate(cpu, models) < 0)
980         return -1;
981 
982     VIR_DEBUG("model=%s", NULLSTR(cpu->model));
983     return 0;
984 }
985 
986 
987 /**
988  * virCPUConvertLegacy:
989  *
990  * @arch: CPU architecture
991  * @cpu: CPU definition to be converted
992  *
993  * Convert legacy CPU definition into one that the corresponding cpu driver
994  * will be able to work with. Currently this is only implemented by the PPC
995  * driver, which needs to convert legacy POWERx_v* names into POWERx.
996  *
997  * Returns -1 on error, 0 on success.
998  */
999 int
virCPUConvertLegacy(virArch arch,virCPUDef * cpu)1000 virCPUConvertLegacy(virArch arch,
1001                     virCPUDef *cpu)
1002 {
1003     struct cpuArchDriver *driver;
1004 
1005     VIR_DEBUG("arch=%s, cpu=%p, model=%s",
1006               virArchToString(arch), cpu, NULLSTR(cpu->model));
1007 
1008     if (!(driver = cpuGetSubDriver(arch)))
1009         return -1;
1010 
1011     if (!driver->convertLegacy)
1012         return 0;
1013 
1014     if (driver->convertLegacy(cpu) < 0)
1015         return -1;
1016 
1017     VIR_DEBUG("model=%s", NULLSTR(cpu->model));
1018     return 0;
1019 }
1020 
1021 
1022 static int
virCPUFeatureCompare(const void * p1,const void * p2)1023 virCPUFeatureCompare(const void *p1,
1024                      const void *p2)
1025 {
1026     const virCPUFeatureDef *f1 = p1;
1027     const virCPUFeatureDef *f2 = p2;
1028 
1029     return strcmp(f1->name, f2->name);
1030 }
1031 
1032 
1033 /**
1034  * virCPUExpandFeatures:
1035  *
1036  * @arch: CPU architecture
1037  * @cpu: CPU definition to be expanded
1038  *
1039  * Add all features implicitly enabled by the CPU model to the list of
1040  * features. The @cpu is expected to be either a host or a guest representation
1041  * of a host CPU, i.e., only VIR_CPU_FEATURE_REQUIRE and
1042  * VIR_CPU_FEATURE_DISABLE policies are supported.
1043  *
1044  * The updated list of features in the CPU definition is sorted.
1045  *
1046  * Return -1 on error, 0 on success.
1047  */
1048 int
virCPUExpandFeatures(virArch arch,virCPUDef * cpu)1049 virCPUExpandFeatures(virArch arch,
1050                      virCPUDef *cpu)
1051 {
1052     struct cpuArchDriver *driver;
1053 
1054     VIR_DEBUG("arch=%s, cpu=%p, model=%s, nfeatures=%zu",
1055               virArchToString(arch), cpu, NULLSTR(cpu->model), cpu->nfeatures);
1056 
1057     if (!(driver = cpuGetSubDriver(arch)))
1058         return -1;
1059 
1060     if (driver->expandFeatures &&
1061         driver->expandFeatures(cpu) < 0)
1062         return -1;
1063 
1064     qsort(cpu->features, cpu->nfeatures, sizeof(*cpu->features),
1065           virCPUFeatureCompare);
1066 
1067     VIR_DEBUG("nfeatures=%zu", cpu->nfeatures);
1068     return 0;
1069 }
1070 
1071 
1072 /**
1073  * virCPUCopyMigratable:
1074  *
1075  * @arch: CPU architecture
1076  * @cpu: CPU definition to be copied
1077  *
1078  * Makes a copy of @cpu with all features which would block migration removed.
1079  * If this doesn't make sense for a given architecture, the function returns a
1080  * plain copy of @cpu (i.e., a copy with no features removed).
1081  *
1082  * Returns the copy of the CPU or NULL on error.
1083  */
1084 virCPUDef *
virCPUCopyMigratable(virArch arch,virCPUDef * cpu)1085 virCPUCopyMigratable(virArch arch,
1086                      virCPUDef *cpu)
1087 {
1088     struct cpuArchDriver *driver;
1089 
1090     VIR_DEBUG("arch=%s, cpu=%p, model=%s",
1091               virArchToString(arch), cpu, NULLSTR(cpu->model));
1092 
1093     if (!(driver = cpuGetSubDriver(arch)))
1094         return NULL;
1095 
1096     if (driver->copyMigratable)
1097         return driver->copyMigratable(cpu);
1098     else
1099         return virCPUDefCopy(cpu);
1100 }
1101 
1102 
1103 /**
1104  * virCPUValidateFeatures:
1105  *
1106  * @arch: CPU architecture
1107  * @cpu: CPU definition to be checked
1108  *
1109  * Checks whether all CPU features specified in @cpu are valid.
1110  *
1111  * Returns 0 on success (all features are valid), -1 on error.
1112  */
1113 int
virCPUValidateFeatures(virArch arch,virCPUDef * cpu)1114 virCPUValidateFeatures(virArch arch,
1115                        virCPUDef *cpu)
1116 {
1117     struct cpuArchDriver *driver;
1118 
1119     VIR_DEBUG("arch=%s, cpu=%p, nfeatures=%zu",
1120               virArchToString(arch), cpu, cpu->nfeatures);
1121 
1122     if (!(driver = cpuGetSubDriver(arch)))
1123         return -1;
1124 
1125     if (driver->validateFeatures)
1126         return driver->validateFeatures(cpu);
1127     else
1128         return 0;
1129 }
1130 
1131 
1132 /**
1133  * virCPUDataAddFeature:
1134  *
1135  * @cpuData: CPU data
1136  * @name: feature to be added to @cpuData
1137  *
1138  * Adds a feature called @name to @cpuData.
1139  *
1140  * Returns 0 on success, -1 on error.
1141  */
1142 int
virCPUDataAddFeature(virCPUData * cpuData,const char * name)1143 virCPUDataAddFeature(virCPUData *cpuData,
1144                      const char *name)
1145 {
1146     struct cpuArchDriver *driver;
1147 
1148     VIR_DEBUG("arch=%s, cpuData=%p, name=%s",
1149               virArchToString(cpuData->arch), cpuData, name);
1150 
1151     if (!(driver = cpuGetSubDriver(cpuData->arch)))
1152         return -1;
1153 
1154     if (!driver->dataAddFeature) {
1155         virReportError(VIR_ERR_NO_SUPPORT,
1156                        _("cannot add guest CPU feature for %s architecture"),
1157                        virArchToString(cpuData->arch));
1158         return -1;
1159     }
1160 
1161     return driver->dataAddFeature(cpuData, name);
1162 }
1163 
1164 
1165 /**
1166  * virCPUDataIsIdentical:
1167  *
1168  * Returns VIR_CPU_COMPARE_IDENTICAL if @a and @b are identical,
1169  * VIR_CPU_COMPARE_INCOMPATIBLE if @a and @b are not identical, or
1170  * VIR_CPU_COMPARE_ERROR on error.
1171  */
1172 virCPUCompareResult
virCPUDataIsIdentical(const virCPUData * a,const virCPUData * b)1173 virCPUDataIsIdentical(const virCPUData *a,
1174                       const virCPUData *b)
1175 {
1176     struct cpuArchDriver *driver;
1177 
1178     VIR_DEBUG("a=%p, b=%p", a, b);
1179 
1180     if (!a || !b)
1181         return VIR_CPU_COMPARE_ERROR;
1182 
1183     if (!(driver = cpuGetSubDriver(a->arch)))
1184         return VIR_CPU_COMPARE_ERROR;
1185 
1186     if (!driver->dataIsIdentical)
1187         return VIR_CPU_COMPARE_ERROR;
1188 
1189     return driver->dataIsIdentical(a, b);
1190 }
1191 
1192 
1193 /**
1194  * virCPUDataGetHost:
1195  *
1196  */
1197 virCPUData*
virCPUDataGetHost(void)1198 virCPUDataGetHost(void)
1199 {
1200     struct cpuArchDriver *driver;
1201 
1202     if (!(driver = cpuGetSubDriver(virArchFromHost())))
1203         return NULL;
1204 
1205     if (!driver->dataGetHost)
1206         return NULL;
1207 
1208     return driver->dataGetHost();
1209 }
1210 
1211 
1212 /**
1213  * virCPUArchIsSupported:
1214  *
1215  * @arch: CPU architecture
1216  *
1217  * Returns true if the architecture is supported by any CPU driver.
1218  */
1219 bool
virCPUArchIsSupported(virArch arch)1220 virCPUArchIsSupported(virArch arch)
1221 {
1222     size_t i;
1223     size_t j;
1224 
1225     for (i = 0; i < G_N_ELEMENTS(drivers); i++) {
1226         for (j = 0; j < drivers[i]->narch; j++) {
1227             if (arch == drivers[i]->arch[j])
1228                 return true;
1229         }
1230     }
1231 
1232     return false;
1233 }
1234