cpu_x86.c 70.4 KB
Newer Older
J
Jiri Denemark 已提交
1 2 3
/*
 * cpu_x86.c: CPU driver for CPUs with x86 compatible CPUID instruction
 *
4
 * Copyright (C) 2009-2014 Red Hat, Inc.
J
Jiri Denemark 已提交
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
J
Jiri Denemark 已提交
19 20 21 22 23 24 25 26 27
 *
 * Authors:
 *      Jiri Denemark <jdenemar@redhat.com>
 */

#include <config.h>

#include <stdint.h>

28
#include "virlog.h"
29
#include "viralloc.h"
J
Jiri Denemark 已提交
30 31 32
#include "cpu.h"
#include "cpu_map.h"
#include "cpu_x86.h"
33
#include "virbuffer.h"
E
Eric Blake 已提交
34
#include "virendian.h"
35
#include "virstring.h"
J
Jiri Denemark 已提交
36 37 38

#define VIR_FROM_THIS VIR_FROM_CPU

39 40
VIR_LOG_INIT("cpu.cpu_x86");

J
Jiri Denemark 已提交
41 42
#define VENDOR_STRING_LENGTH    12

43
static const virCPUx86CPUID cpuidNull = { 0 };
J
Jiri Denemark 已提交
44

45
static const virArch archs[] = { VIR_ARCH_I686, VIR_ARCH_X86_64 };
J
Jiri Denemark 已提交
46

47 48 49
typedef struct _virCPUx86Vendor virCPUx86Vendor;
typedef virCPUx86Vendor *virCPUx86VendorPtr;
struct _virCPUx86Vendor {
J
Jiri Denemark 已提交
50
    char *name;
51
    virCPUx86CPUID cpuid;
J
Jiri Denemark 已提交
52 53
};

54 55 56
typedef struct _virCPUx86Feature virCPUx86Feature;
typedef virCPUx86Feature *virCPUx86FeaturePtr;
struct _virCPUx86Feature {
J
Jiri Denemark 已提交
57
    char *name;
58
    virCPUx86Data data;
J
Jiri Denemark 已提交
59
    bool migratable;
J
Jiri Denemark 已提交
60 61
};

62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#define KVM_FEATURE_DEF(Name, Eax_in, Eax)                          \
    static virCPUx86CPUID Name ## _cpuid[] = {                      \
        { .eax_in = Eax_in, .eax = Eax },                           \
    }

#define KVM_FEATURE(Name)                                           \
    {                                                               \
        .name = (char *) Name,                                      \
        .data = {                                                   \
            .len = ARRAY_CARDINALITY(Name ## _cpuid),               \
            .data = Name ## _cpuid                                  \
        }                                                           \
    }

KVM_FEATURE_DEF(VIR_CPU_x86_KVM_CLOCKSOURCE,
                0x40000001, 0x00000001);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_NOP_IO_DELAY,
                0x40000001, 0x00000002);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_MMU_OP,
                0x40000001, 0x00000004);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_CLOCKSOURCE2,
                0x40000001, 0x00000008);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_ASYNC_PF,
                0x40000001, 0x00000010);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_STEAL_TIME,
                0x40000001, 0x00000020);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_PV_EOI,
                0x40000001, 0x00000040);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_PV_UNHALT,
                0x40000001, 0x00000080);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_CLOCKSOURCE_STABLE_BIT,
                0x40000001, 0x01000000);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_RUNTIME,
                0x40000003, 0x00000001);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_SYNIC,
                0x40000003, 0x00000004);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_STIMER,
                0x40000003, 0x00000008);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_RELAXED,
                0x40000003, 0x00000020);
103
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_SPINLOCKS,
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
                0x40000003, 0x00000022);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_VAPIC,
                0x40000003, 0x00000030);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_VPINDEX,
                0x40000003, 0x00000040);
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_RESET,
                0x40000003, 0x00000080);

static virCPUx86Feature x86_kvm_features[] =
{
    KVM_FEATURE(VIR_CPU_x86_KVM_CLOCKSOURCE),
    KVM_FEATURE(VIR_CPU_x86_KVM_NOP_IO_DELAY),
    KVM_FEATURE(VIR_CPU_x86_KVM_MMU_OP),
    KVM_FEATURE(VIR_CPU_x86_KVM_CLOCKSOURCE2),
    KVM_FEATURE(VIR_CPU_x86_KVM_ASYNC_PF),
    KVM_FEATURE(VIR_CPU_x86_KVM_STEAL_TIME),
    KVM_FEATURE(VIR_CPU_x86_KVM_PV_EOI),
    KVM_FEATURE(VIR_CPU_x86_KVM_PV_UNHALT),
    KVM_FEATURE(VIR_CPU_x86_KVM_CLOCKSOURCE_STABLE_BIT),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_RUNTIME),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_SYNIC),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_STIMER),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_RELAXED),
127
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_SPINLOCKS),
128 129 130
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_VAPIC),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_VPINDEX),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_RESET),
131 132
};

J
Jiri Denemark 已提交
133 134 135
typedef struct _virCPUx86Model virCPUx86Model;
typedef virCPUx86Model *virCPUx86ModelPtr;
struct _virCPUx86Model {
J
Jiri Denemark 已提交
136
    char *name;
137
    virCPUx86VendorPtr vendor;
138
    uint32_t signature;
139
    virCPUx86Data data;
J
Jiri Denemark 已提交
140 141
};

J
Jiri Denemark 已提交
142 143 144
typedef struct _virCPUx86Map virCPUx86Map;
typedef virCPUx86Map *virCPUx86MapPtr;
struct _virCPUx86Map {
145 146
    size_t nvendors;
    virCPUx86VendorPtr *vendors;
147 148
    size_t nfeatures;
    virCPUx86FeaturePtr *features;
149 150
    size_t nmodels;
    virCPUx86ModelPtr *models;
151 152
    size_t nblockers;
    virCPUx86FeaturePtr *migrate_blockers;
J
Jiri Denemark 已提交
153 154
};

J
Jiri Denemark 已提交
155
static virCPUx86MapPtr cpuMap;
156 157 158
int virCPUx86MapOnceInit(void);
VIR_ONCE_GLOBAL_INIT(virCPUx86Map);

J
Jiri Denemark 已提交
159

160
typedef enum {
J
Jiri Denemark 已提交
161 162 163 164
    SUBSET,
    EQUAL,
    SUPERSET,
    UNRELATED
165
} virCPUx86CompareResult;
J
Jiri Denemark 已提交
166 167


168 169 170
typedef struct _virCPUx86DataIterator virCPUx86DataIterator;
typedef virCPUx86DataIterator *virCPUx86DataIteratorPtr;
struct _virCPUx86DataIterator {
171
    const virCPUx86Data *data;
J
Jiri Denemark 已提交
172 173
    int pos;
};
J
Jiri Denemark 已提交
174 175


176
#define virCPUx86DataIteratorInit(data) \
177
    { data, -1 }
J
Jiri Denemark 已提交
178 179


180
static bool
181 182
x86cpuidMatch(const virCPUx86CPUID *cpuid1,
              const virCPUx86CPUID *cpuid2)
J
Jiri Denemark 已提交
183 184 185 186 187 188 189 190
{
    return (cpuid1->eax == cpuid2->eax &&
            cpuid1->ebx == cpuid2->ebx &&
            cpuid1->ecx == cpuid2->ecx &&
            cpuid1->edx == cpuid2->edx);
}


191
static bool
192 193
x86cpuidMatchMasked(const virCPUx86CPUID *cpuid,
                    const virCPUx86CPUID *mask)
J
Jiri Denemark 已提交
194 195 196 197 198 199 200 201
{
    return ((cpuid->eax & mask->eax) == mask->eax &&
            (cpuid->ebx & mask->ebx) == mask->ebx &&
            (cpuid->ecx & mask->ecx) == mask->ecx &&
            (cpuid->edx & mask->edx) == mask->edx);
}


J
Jiri Denemark 已提交
202
static void
203 204
x86cpuidSetBits(virCPUx86CPUID *cpuid,
                const virCPUx86CPUID *mask)
J
Jiri Denemark 已提交
205
{
206 207 208
    if (!mask)
        return;

J
Jiri Denemark 已提交
209 210 211 212 213 214 215
    cpuid->eax |= mask->eax;
    cpuid->ebx |= mask->ebx;
    cpuid->ecx |= mask->ecx;
    cpuid->edx |= mask->edx;
}


J
Jiri Denemark 已提交
216
static void
217 218
x86cpuidClearBits(virCPUx86CPUID *cpuid,
                  const virCPUx86CPUID *mask)
J
Jiri Denemark 已提交
219
{
220 221 222
    if (!mask)
        return;

J
Jiri Denemark 已提交
223 224 225 226 227 228 229
    cpuid->eax &= ~mask->eax;
    cpuid->ebx &= ~mask->ebx;
    cpuid->ecx &= ~mask->ecx;
    cpuid->edx &= ~mask->edx;
}


J
Jiri Denemark 已提交
230
static void
231 232
x86cpuidAndBits(virCPUx86CPUID *cpuid,
                const virCPUx86CPUID *mask)
233
{
234 235 236
    if (!mask)
        return;

237 238 239 240 241 242
    cpuid->eax &= mask->eax;
    cpuid->ebx &= mask->ebx;
    cpuid->ecx &= mask->ecx;
    cpuid->edx &= mask->edx;
}

243 244 245 246 247 248
static int
virCPUx86CPUIDSorter(const void *a, const void *b)
{
    virCPUx86CPUID *da = (virCPUx86CPUID *) a;
    virCPUx86CPUID *db = (virCPUx86CPUID *) b;

249
    if (da->eax_in > db->eax_in)
250
        return 1;
251
    else if (da->eax_in < db->eax_in)
252 253
        return -1;

254 255 256 257 258
    if (da->ecx_in > db->ecx_in)
        return 1;
    else if (da->ecx_in < db->ecx_in)
        return -1;

259 260 261
    return 0;
}

262

263
/* skips all zero CPUID leaves */
264
static virCPUx86CPUID *
265
x86DataCpuidNext(virCPUx86DataIteratorPtr iterator)
J
Jiri Denemark 已提交
266
{
267
    const virCPUx86Data *data = iterator->data;
J
Jiri Denemark 已提交
268

269
    if (!data)
J
Jiri Denemark 已提交
270 271
        return NULL;

272 273 274 275
    while (++iterator->pos < data->len) {
        if (!x86cpuidMatch(data->data + iterator->pos, &cpuidNull))
            return data->data + iterator->pos;
    }
J
Jiri Denemark 已提交
276

277
    return NULL;
J
Jiri Denemark 已提交
278 279 280
}


281
static virCPUx86CPUID *
282
x86DataCpuid(const virCPUx86Data *data,
283
             const virCPUx86CPUID *cpuid)
J
Jiri Denemark 已提交
284
{
285
    size_t i;
J
Jiri Denemark 已提交
286

287
    for (i = 0; i < data->len; i++) {
288 289
        if (data->data[i].eax_in == cpuid->eax_in &&
            data->data[i].ecx_in == cpuid->ecx_in)
290
            return data->data + i;
J
Jiri Denemark 已提交
291 292
    }

293
    return NULL;
J
Jiri Denemark 已提交
294 295
}

296
static void
297
virCPUx86DataClear(virCPUx86Data *data)
J
Jiri Denemark 已提交
298
{
299
    if (!data)
J
Jiri Denemark 已提交
300 301
        return;

302
    VIR_FREE(data->data);
J
Jiri Denemark 已提交
303 304 305
}


306
static void
307
x86FreeCPUData(virCPUDataPtr data)
308 309 310 311
{
    if (!data)
        return;

312
    virCPUx86DataClear(&data->data.x86);
313 314 315 316
    VIR_FREE(data);
}


317 318
static int
x86DataCopy(virCPUx86Data *dst, const virCPUx86Data *src)
J
Jiri Denemark 已提交
319
{
320
    size_t i;
J
Jiri Denemark 已提交
321

322 323
    if (VIR_ALLOC_N(dst->data, src->len) < 0)
        return -1;
J
Jiri Denemark 已提交
324

325 326 327
    dst->len = src->len;
    for (i = 0; i < src->len; i++)
        dst->data[i] = src->data[i];
J
Jiri Denemark 已提交
328

329
    return 0;
J
Jiri Denemark 已提交
330 331 332
}


J
Jiri Denemark 已提交
333
int
334 335
virCPUx86DataAddCPUID(virCPUx86Data *data,
                      const virCPUx86CPUID *cpuid)
J
Jiri Denemark 已提交
336
{
337
    virCPUx86CPUID *existing;
J
Jiri Denemark 已提交
338

339
    if ((existing = x86DataCpuid(data, cpuid))) {
340 341 342 343 344
        x86cpuidSetBits(existing, cpuid);
    } else {
        if (VIR_APPEND_ELEMENT_COPY(data->data, data->len,
                                    *((virCPUx86CPUID *)cpuid)) < 0)
            return -1;
J
Jiri Denemark 已提交
345

346 347 348
        qsort(data->data, data->len,
              sizeof(virCPUx86CPUID), virCPUx86CPUIDSorter);
    }
J
Jiri Denemark 已提交
349

J
Jiri Denemark 已提交
350 351 352 353 354
    return 0;
}


static int
355 356
x86DataAdd(virCPUx86Data *data1,
           const virCPUx86Data *data2)
J
Jiri Denemark 已提交
357
{
358
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data2);
359 360
    virCPUx86CPUID *cpuid1;
    virCPUx86CPUID *cpuid2;
J
Jiri Denemark 已提交
361

362
    while ((cpuid2 = x86DataCpuidNext(&iter))) {
363
        cpuid1 = x86DataCpuid(data1, cpuid2);
J
Jiri Denemark 已提交
364

365 366 367 368 369 370
        if (cpuid1) {
            x86cpuidSetBits(cpuid1, cpuid2);
        } else {
            if (virCPUx86DataAddCPUID(data1, cpuid2) < 0)
                return -1;
        }
J
Jiri Denemark 已提交
371
    }
J
Jiri Denemark 已提交
372 373 374 375 376

    return 0;
}


377
static void
378 379
x86DataSubtract(virCPUx86Data *data1,
                const virCPUx86Data *data2)
380
{
381
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data1);
382 383
    virCPUx86CPUID *cpuid1;
    virCPUx86CPUID *cpuid2;
384

385
    while ((cpuid1 = x86DataCpuidNext(&iter))) {
386
        cpuid2 = x86DataCpuid(data2, cpuid1);
387
        x86cpuidClearBits(cpuid1, cpuid2);
388 389 390 391
    }
}


J
Jiri Denemark 已提交
392
static void
393 394
x86DataIntersect(virCPUx86Data *data1,
                 const virCPUx86Data *data2)
395
{
396
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data1);
397 398
    virCPUx86CPUID *cpuid1;
    virCPUx86CPUID *cpuid2;
399

J
Jiri Denemark 已提交
400
    while ((cpuid1 = x86DataCpuidNext(&iter))) {
401
        cpuid2 = x86DataCpuid(data2, cpuid1);
J
Jiri Denemark 已提交
402 403 404 405
        if (cpuid2)
            x86cpuidAndBits(cpuid1, cpuid2);
        else
            x86cpuidClearBits(cpuid1, cpuid1);
406 407 408 409
    }
}


J
Jiri Denemark 已提交
410
static bool
411
x86DataIsEmpty(virCPUx86Data *data)
J
Jiri Denemark 已提交
412
{
413
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data);
J
Jiri Denemark 已提交
414

415
    return !x86DataCpuidNext(&iter);
J
Jiri Denemark 已提交
416
}
J
Jiri Denemark 已提交
417 418


J
Jiri Denemark 已提交
419
static bool
420 421
x86DataIsSubset(const virCPUx86Data *data,
                const virCPUx86Data *subset)
J
Jiri Denemark 已提交
422 423
{

424
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit((virCPUx86Data *)subset);
425 426
    const virCPUx86CPUID *cpuid;
    const virCPUx86CPUID *cpuidSubset;
J
Jiri Denemark 已提交
427

J
Jiri Denemark 已提交
428
    while ((cpuidSubset = x86DataCpuidNext(&iter))) {
429
        if (!(cpuid = x86DataCpuid(data, cpuidSubset)) ||
J
Jiri Denemark 已提交
430 431
            !x86cpuidMatchMasked(cpuid, cpuidSubset))
            return false;
J
Jiri Denemark 已提交
432 433
    }

J
Jiri Denemark 已提交
434
    return true;
J
Jiri Denemark 已提交
435 436 437
}


438 439 440 441
/* also removes all detected features from data */
static int
x86DataToCPUFeatures(virCPUDefPtr cpu,
                     int policy,
442
                     virCPUx86Data *data,
J
Jiri Denemark 已提交
443
                     virCPUx86MapPtr map)
444
{
445
    size_t i;
446

447 448
    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];
449 450
        if (x86DataIsSubset(data, &feature->data)) {
            x86DataSubtract(data, &feature->data);
J
Jiri Denemark 已提交
451 452
            if (virCPUDefAddFeature(cpu, feature->name, policy) < 0)
                return -1;
453 454 455 456 457 458 459
        }
    }

    return 0;
}


J
Jiri Denemark 已提交
460
/* also removes bits corresponding to vendor string from data */
461
static virCPUx86VendorPtr
J
Jiri Denemark 已提交
462
x86DataToVendor(const virCPUx86Data *data,
J
Jiri Denemark 已提交
463
                virCPUx86MapPtr map)
J
Jiri Denemark 已提交
464
{
465
    virCPUx86CPUID *cpuid;
466
    size_t i;
J
Jiri Denemark 已提交
467

468 469
    for (i = 0; i < map->nvendors; i++) {
        virCPUx86VendorPtr vendor = map->vendors[i];
470
        if ((cpuid = x86DataCpuid(data, &vendor->cpuid)) &&
J
Jiri Denemark 已提交
471 472 473 474 475 476 477 478 479 480
            x86cpuidMatchMasked(cpuid, &vendor->cpuid)) {
            x86cpuidClearBits(cpuid, &vendor->cpuid);
            return vendor;
        }
    }

    return NULL;
}


481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
static uint32_t
x86MakeSignature(unsigned int family,
                 unsigned int model)
{
    uint32_t sig = 0;

    /*
     * CPU signature (eax from 0x1 CPUID leaf):
     *
     * |31 .. 28|27 .. 20|19 .. 16|15 .. 14|13 .. 12|11 .. 8|7 .. 4|3 .. 0|
     * |   R    | extFam | extMod |   R    | PType  |  Fam  | Mod  | Step |
     *
     * R        reserved
     * extFam   extended family (valid only if Fam == 0xf)
     * extMod   extended model
     * PType    processor type
     * Fam      family
     * Mod      model
     * Step     stepping
     *
     * family = eax[27:20] + eax[11:8]
     * model = eax[19:16] << 4 + eax[7:4]
     */

    /* extFam */
    if (family > 0xf) {
        sig |= (family - 0xf) << 20;
        family = 0xf;
    }

    /* extMod */
    sig |= (model >> 4) << 16;

    /* PType is always 0 */

    /* Fam */
    sig |= family << 8;

    /* Mod */
    sig |= (model & 0xf) << 4;

    /* Step is irrelevant, it is used to distinguish different revisions
     * of the same CPU model
     */

    return sig;
}


/* Mask out irrelevant bits (R and Step) from processor signature. */
#define SIGNATURE_MASK  0x0fff3ff0

static uint32_t
x86DataToSignature(const virCPUx86Data *data)
{
    virCPUx86CPUID leaf1 = { .eax_in = 0x1 };
    virCPUx86CPUID *cpuid;

    if (!(cpuid = x86DataCpuid(data, &leaf1)))
        return 0;

    return cpuid->eax & SIGNATURE_MASK;
}


static int
x86DataAddSignature(virCPUx86Data *data,
                    uint32_t signature)
{
    virCPUx86CPUID cpuid = { .eax_in = 0x1, .eax = signature };

    return virCPUx86DataAddCPUID(data, &cpuid);
}


556
static virCPUDefPtr
557
x86DataToCPU(const virCPUx86Data *data,
J
Jiri Denemark 已提交
558
             virCPUx86ModelPtr model,
J
Jiri Denemark 已提交
559
             virCPUx86MapPtr map)
560 561
{
    virCPUDefPtr cpu;
562 563
    virCPUx86Data copy = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data modelData = VIR_CPU_X86_DATA_INIT;
564
    virCPUx86VendorPtr vendor;
565 566

    if (VIR_ALLOC(cpu) < 0 ||
567
        VIR_STRDUP(cpu->model, model->name) < 0 ||
568 569
        x86DataCopy(&copy, data) < 0 ||
        x86DataCopy(&modelData, &model->data) < 0)
570
        goto error;
571

572
    if ((vendor = x86DataToVendor(&copy, map)) &&
573
        VIR_STRDUP(cpu->vendor, vendor->name) < 0)
574
        goto error;
J
Jiri Denemark 已提交
575

576 577
    x86DataSubtract(&copy, &modelData);
    x86DataSubtract(&modelData, data);
578 579 580

    /* because feature policy is ignored for host CPU */
    cpu->type = VIR_CPU_TYPE_GUEST;
581

582 583
    if (x86DataToCPUFeatures(cpu, VIR_CPU_FEATURE_REQUIRE, &copy, map) ||
        x86DataToCPUFeatures(cpu, VIR_CPU_FEATURE_DISABLE, &modelData, map))
584
        goto error;
585

586
 cleanup:
587 588
    virCPUx86DataClear(&modelData);
    virCPUx86DataClear(&copy);
589 590
    return cpu;

591
 error:
592 593 594 595 596 597
    virCPUDefFree(cpu);
    cpu = NULL;
    goto cleanup;
}


J
Jiri Denemark 已提交
598
static void
599
x86VendorFree(virCPUx86VendorPtr vendor)
J
Jiri Denemark 已提交
600 601 602 603 604 605
{
    if (!vendor)
        return;

    VIR_FREE(vendor->name);
    VIR_FREE(vendor);
J
Jiri Denemark 已提交
606
}
J
Jiri Denemark 已提交
607 608


609
static virCPUx86VendorPtr
J
Jiri Denemark 已提交
610
x86VendorFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
611 612
              const char *name)
{
613
    size_t i;
J
Jiri Denemark 已提交
614

615 616 617
    for (i = 0; i < map->nvendors; i++) {
        if (STREQ(map->vendors[i]->name, name))
            return map->vendors[i];
J
Jiri Denemark 已提交
618 619 620 621 622 623
    }

    return NULL;
}


J
Jiri Denemark 已提交
624 625 626
static virCPUx86VendorPtr
x86VendorParse(xmlXPathContextPtr ctxt,
               virCPUx86MapPtr map)
J
Jiri Denemark 已提交
627
{
628
    virCPUx86VendorPtr vendor = NULL;
J
Jiri Denemark 已提交
629 630 631
    char *string = NULL;

    if (VIR_ALLOC(vendor) < 0)
J
Jiri Denemark 已提交
632
        goto error;
J
Jiri Denemark 已提交
633 634 635

    vendor->name = virXPathString("string(@name)", ctxt);
    if (!vendor->name) {
636 637
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing CPU vendor name"));
J
Jiri Denemark 已提交
638
        goto error;
J
Jiri Denemark 已提交
639 640 641
    }

    if (x86VendorFind(map, vendor->name)) {
642 643
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU vendor %s already defined"), vendor->name);
J
Jiri Denemark 已提交
644
        goto error;
J
Jiri Denemark 已提交
645 646 647 648
    }

    string = virXPathString("string(@string)", ctxt);
    if (!string) {
649
        virReportError(VIR_ERR_INTERNAL_ERROR,
650 651
                       _("Missing vendor string for CPU vendor %s"),
                       vendor->name);
J
Jiri Denemark 已提交
652
        goto error;
J
Jiri Denemark 已提交
653 654
    }
    if (strlen(string) != VENDOR_STRING_LENGTH) {
655 656
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid CPU vendor string '%s'"), string);
J
Jiri Denemark 已提交
657
        goto error;
J
Jiri Denemark 已提交
658 659
    }

660
    vendor->cpuid.eax_in = 0;
661
    vendor->cpuid.ecx_in = 0;
E
Eric Blake 已提交
662 663 664 665
    vendor->cpuid.ebx = virReadBufInt32LE(string);
    vendor->cpuid.edx = virReadBufInt32LE(string + 4);
    vendor->cpuid.ecx = virReadBufInt32LE(string + 8);

J
Jiri Denemark 已提交
666
 cleanup:
J
Jiri Denemark 已提交
667
    VIR_FREE(string);
J
Jiri Denemark 已提交
668 669 670
    return vendor;

 error:
J
Jiri Denemark 已提交
671
    x86VendorFree(vendor);
J
Jiri Denemark 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    vendor = NULL;
    goto cleanup;
}


static int
x86VendorsLoad(virCPUx86MapPtr map,
               xmlXPathContextPtr ctxt,
               xmlNodePtr *nodes,
               int n)
{
    virCPUx86VendorPtr vendor;
    size_t i;

    if (VIR_ALLOC_N(map->vendors, n) < 0)
        return -1;

    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
        if (!(vendor = x86VendorParse(ctxt, map)))
            return -1;
        map->vendors[map->nvendors++] = vendor;
    }

    return 0;
J
Jiri Denemark 已提交
697 698 699
}


700
static virCPUx86FeaturePtr
J
Jiri Denemark 已提交
701 702
x86FeatureNew(void)
{
703
    virCPUx86FeaturePtr feature;
J
Jiri Denemark 已提交
704 705 706 707 708 709 710 711

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

    return feature;
}


J
Jiri Denemark 已提交
712
static void
713
x86FeatureFree(virCPUx86FeaturePtr feature)
J
Jiri Denemark 已提交
714
{
715
    if (!feature)
J
Jiri Denemark 已提交
716 717 718
        return;

    VIR_FREE(feature->name);
719
    virCPUx86DataClear(&feature->data);
J
Jiri Denemark 已提交
720 721 722 723
    VIR_FREE(feature);
}


724
static virCPUx86FeaturePtr
J
Jiri Denemark 已提交
725
x86FeatureFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
726 727
               const char *name)
{
728
    size_t i;
J
Jiri Denemark 已提交
729

730 731 732
    for (i = 0; i < map->nfeatures; i++) {
        if (STREQ(map->features[i]->name, name))
            return map->features[i];
J
Jiri Denemark 已提交
733 734 735 736 737 738
    }

    return NULL;
}


739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
static virCPUx86FeaturePtr
x86FeatureFindInternal(const char *name)
{
    size_t i;
    size_t count = ARRAY_CARDINALITY(x86_kvm_features);

    for (i = 0; i < count; i++) {
        if (STREQ(x86_kvm_features[i].name, name))
            return x86_kvm_features + i;
    }

    return NULL;
}


J
Jiri Denemark 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
static int
x86FeatureInData(const char *name,
                 const virCPUx86Data *data,
                 virCPUx86MapPtr map)
{
    virCPUx86FeaturePtr feature;

    if (!(feature = x86FeatureFind(map, name)) &&
        !(feature = x86FeatureFindInternal(name))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown CPU feature %s"), name);
        return -1;
    }

    if (x86DataIsSubset(data, &feature->data))
        return 1;
    else
        return 0;
}


775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
static bool
x86FeatureIsMigratable(const char *name,
                       void *cpu_map)
{
    virCPUx86MapPtr map = cpu_map;
    size_t i;

    for (i = 0; i < map->nblockers; i++) {
        if (STREQ(name, map->migrate_blockers[i]->name))
            return false;
    }

    return true;
}


791
static char *
J
Jiri Denemark 已提交
792
x86FeatureNames(virCPUx86MapPtr map,
793
                const char *separator,
794
                virCPUx86Data *data)
795 796 797
{
    virBuffer ret = VIR_BUFFER_INITIALIZER;
    bool first = true;
798
    size_t i;
799 800 801

    virBufferAdd(&ret, "", 0);

802 803
    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];
804
        if (x86DataIsSubset(data, &feature->data)) {
805 806 807 808 809
            if (!first)
                virBufferAdd(&ret, separator, -1);
            else
                first = false;

810
            virBufferAdd(&ret, feature->name, -1);
811 812 813 814 815 816 817
        }
    }

    return virBufferContentAndReset(&ret);
}


818 819
static int
x86ParseCPUID(xmlXPathContextPtr ctxt,
820
              virCPUx86CPUID *cpuid)
821
{
822
    unsigned long eax_in, ecx_in;
823
    unsigned long eax, ebx, ecx, edx;
824
    int ret_eax_in, ret_ecx_in, ret_eax, ret_ebx, ret_ecx, ret_edx;
825 826 827

    memset(cpuid, 0, sizeof(*cpuid));

828
    eax_in = ecx_in = 0;
829 830
    eax = ebx = ecx = edx = 0;
    ret_eax_in = virXPathULongHex("string(@eax_in)", ctxt, &eax_in);
831
    ret_ecx_in = virXPathULongHex("string(@ecx_in)", ctxt, &ecx_in);
832 833 834 835 836
    ret_eax = virXPathULongHex("string(@eax)", ctxt, &eax);
    ret_ebx = virXPathULongHex("string(@ebx)", ctxt, &ebx);
    ret_ecx = virXPathULongHex("string(@ecx)", ctxt, &ecx);
    ret_edx = virXPathULongHex("string(@edx)", ctxt, &edx);

837
    if (ret_eax_in < 0 || ret_ecx_in == -2 ||
838
        ret_eax == -2 || ret_ebx == -2 || ret_ecx == -2 || ret_edx == -2)
839 840
        return -1;

841
    cpuid->eax_in = eax_in;
842
    cpuid->ecx_in = ecx_in;
843 844 845 846 847 848 849 850
    cpuid->eax = eax;
    cpuid->ebx = ebx;
    cpuid->ecx = ecx;
    cpuid->edx = edx;
    return 0;
}


J
Jiri Denemark 已提交
851 852 853
static virCPUx86FeaturePtr
x86FeatureParse(xmlXPathContextPtr ctxt,
                virCPUx86MapPtr map)
J
Jiri Denemark 已提交
854 855
{
    xmlNodePtr *nodes = NULL;
856
    virCPUx86FeaturePtr feature;
857
    virCPUx86CPUID cpuid;
858
    size_t i;
J
Jiri Denemark 已提交
859
    int n;
860
    char *str = NULL;
J
Jiri Denemark 已提交
861

J
Jiri Denemark 已提交
862
    if (!(feature = x86FeatureNew()))
J
Jiri Denemark 已提交
863
        goto error;
J
Jiri Denemark 已提交
864

J
Jiri Denemark 已提交
865
    feature->migratable = true;
866
    feature->name = virXPathString("string(@name)", ctxt);
867
    if (!feature->name) {
868 869
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Missing CPU feature name"));
J
Jiri Denemark 已提交
870
        goto error;
J
Jiri Denemark 已提交
871 872 873
    }

    if (x86FeatureFind(map, feature->name)) {
874 875
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU feature %s already defined"), feature->name);
J
Jiri Denemark 已提交
876
        goto error;
J
Jiri Denemark 已提交
877 878
    }

879 880
    str = virXPathString("string(@migratable)", ctxt);
    if (STREQ_NULLABLE(str, "no"))
J
Jiri Denemark 已提交
881
        feature->migratable = false;
882

883
    n = virXPathNodeSet("./cpuid", ctxt, &nodes);
J
Jiri Denemark 已提交
884
    if (n < 0)
J
Jiri Denemark 已提交
885
        goto error;
J
Jiri Denemark 已提交
886 887 888

    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
889
        if (x86ParseCPUID(ctxt, &cpuid) < 0) {
890
            virReportError(VIR_ERR_INTERNAL_ERROR,
891 892
                           _("Invalid cpuid[%zu] in %s feature"),
                           i, feature->name);
J
Jiri Denemark 已提交
893
            goto error;
J
Jiri Denemark 已提交
894
        }
895
        if (virCPUx86DataAddCPUID(&feature->data, &cpuid))
J
Jiri Denemark 已提交
896
            goto error;
J
Jiri Denemark 已提交
897 898
    }

J
Jiri Denemark 已提交
899
 cleanup:
900
    VIR_FREE(nodes);
901
    VIR_FREE(str);
J
Jiri Denemark 已提交
902
    return feature;
903

J
Jiri Denemark 已提交
904 905 906 907
 error:
    x86FeatureFree(feature);
    feature = NULL;
    goto cleanup;
J
Jiri Denemark 已提交
908 909 910
}


J
Jiri Denemark 已提交
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
static int
x86FeaturesLoad(virCPUx86MapPtr map,
                xmlXPathContextPtr ctxt,
                xmlNodePtr *nodes,
                int n)
{
    virCPUx86FeaturePtr feature;
    size_t i;

    if (VIR_ALLOC_N(map->features, n) < 0)
        return -1;

    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
        if (!(feature = x86FeatureParse(ctxt, map)))
            return -1;
        map->features[map->nfeatures++] = feature;
        if (!feature->migratable &&
            VIR_APPEND_ELEMENT(map->migrate_blockers,
                               map->nblockers,
                               feature) < 0)
            return -1;
    }

    return 0;
}

938 939 940
static int
x86DataFromCPUFeatures(virCPUx86Data *data,
                       virCPUDefPtr cpu,
J
Jiri Denemark 已提交
941
                       virCPUx86MapPtr map)
942 943 944 945
{
    size_t i;

    for (i = 0; i < cpu->nfeatures; i++) {
946
        virCPUx86FeaturePtr feature;
947 948 949
        if (!(feature = x86FeatureFind(map, cpu->features[i].name))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU feature %s"), cpu->features[i].name);
950
            return -1;
951 952
        }

953 954
        if (x86DataAdd(data, &feature->data) < 0)
            return -1;
955 956
    }

957
    return 0;
958 959 960
}


J
Jiri Denemark 已提交
961
static virCPUx86ModelPtr
J
Jiri Denemark 已提交
962 963
x86ModelNew(void)
{
J
Jiri Denemark 已提交
964
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
965 966 967 968 969 970 971 972

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

    return model;
}


J
Jiri Denemark 已提交
973
static void
J
Jiri Denemark 已提交
974
x86ModelFree(virCPUx86ModelPtr model)
J
Jiri Denemark 已提交
975
{
976
    if (!model)
J
Jiri Denemark 已提交
977 978 979
        return;

    VIR_FREE(model->name);
980
    virCPUx86DataClear(&model->data);
J
Jiri Denemark 已提交
981 982 983 984
    VIR_FREE(model);
}


J
Jiri Denemark 已提交
985 986
static virCPUx86ModelPtr
x86ModelCopy(virCPUx86ModelPtr model)
J
Jiri Denemark 已提交
987
{
J
Jiri Denemark 已提交
988
    virCPUx86ModelPtr copy;
J
Jiri Denemark 已提交
989

990 991
    if (VIR_ALLOC(copy) < 0 ||
        VIR_STRDUP(copy->name, model->name) < 0 ||
992
        x86DataCopy(&copy->data, &model->data) < 0) {
J
Jiri Denemark 已提交
993 994 995 996
        x86ModelFree(copy);
        return NULL;
    }

J
Jiri Denemark 已提交
997
    copy->vendor = model->vendor;
998
    copy->signature = model->signature;
J
Jiri Denemark 已提交
999 1000 1001 1002 1003

    return copy;
}


J
Jiri Denemark 已提交
1004
static virCPUx86ModelPtr
J
Jiri Denemark 已提交
1005
x86ModelFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
1006 1007
             const char *name)
{
1008
    size_t i;
J
Jiri Denemark 已提交
1009

1010 1011 1012
    for (i = 0; i < map->nmodels; i++) {
        if (STREQ(map->models[i]->name, name))
            return map->models[i];
J
Jiri Denemark 已提交
1013 1014 1015 1016 1017 1018
    }

    return NULL;
}


1019 1020 1021 1022 1023 1024 1025 1026 1027
/*
 * Computes CPU model data from a CPU definition associated with features
 * matching @policy. If @policy equals -1, the computed model will describe
 * all CPU features, i.e., it will contain:
 *
 *      features from model
 *      + required and forced features
 *      - disabled and forbidden features
 */
J
Jiri Denemark 已提交
1028
static virCPUx86ModelPtr
1029
x86ModelFromCPU(const virCPUDef *cpu,
J
Jiri Denemark 已提交
1030
                virCPUx86MapPtr map,
J
Jiri Denemark 已提交
1031 1032
                int policy)
{
J
Jiri Denemark 已提交
1033
    virCPUx86ModelPtr model = NULL;
1034
    size_t i;
J
Jiri Denemark 已提交
1035

1036 1037 1038 1039
    /* host CPU only contains required features; requesting other features
     * just returns an empty model
     */
    if (cpu->type == VIR_CPU_TYPE_HOST &&
1040 1041
        policy != VIR_CPU_FEATURE_REQUIRE &&
        policy != -1)
1042 1043
        return x86ModelNew();

J
Jiri Denemark 已提交
1044 1045
    if (cpu->model &&
        (policy == VIR_CPU_FEATURE_REQUIRE || policy == -1)) {
1046
        if (!(model = x86ModelFind(map, cpu->model))) {
1047 1048
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU model %s"), cpu->model);
1049
            return NULL;
J
Jiri Denemark 已提交
1050 1051
        }

1052 1053 1054
        model = x86ModelCopy(model);
    } else {
        model = x86ModelNew();
J
Jiri Denemark 已提交
1055
    }
J
Jiri Denemark 已提交
1056

1057 1058 1059
    if (!model)
        return NULL;

J
Jiri Denemark 已提交
1060
    for (i = 0; i < cpu->nfeatures; i++) {
1061
        virCPUx86FeaturePtr feature;
1062
        virCPUFeaturePolicy fpol;
J
Jiri Denemark 已提交
1063

1064 1065 1066 1067 1068 1069 1070
        if (cpu->features[i].policy == -1)
            fpol = VIR_CPU_FEATURE_REQUIRE;
        else
            fpol = cpu->features[i].policy;

        if ((policy == -1 && fpol == VIR_CPU_FEATURE_OPTIONAL) ||
            (policy != -1 && fpol != policy))
J
Jiri Denemark 已提交
1071 1072
            continue;

1073
        if (!(feature = x86FeatureFind(map, cpu->features[i].name))) {
1074 1075
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU feature %s"), cpu->features[i].name);
J
Jiri Denemark 已提交
1076 1077 1078
            goto error;
        }

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        if (policy == -1) {
            switch (fpol) {
            case VIR_CPU_FEATURE_FORCE:
            case VIR_CPU_FEATURE_REQUIRE:
                if (x86DataAdd(&model->data, &feature->data) < 0)
                    goto error;
                break;

            case VIR_CPU_FEATURE_DISABLE:
            case VIR_CPU_FEATURE_FORBID:
                x86DataSubtract(&model->data, &feature->data);
                break;

            /* coverity[dead_error_condition] */
            case VIR_CPU_FEATURE_OPTIONAL:
            case VIR_CPU_FEATURE_LAST:
                break;
            }
        } else if (x86DataAdd(&model->data, &feature->data) < 0) {
1098
            goto error;
1099
        }
J
Jiri Denemark 已提交
1100 1101 1102 1103
    }

    return model;

1104
 error:
J
Jiri Denemark 已提交
1105 1106 1107 1108 1109
    x86ModelFree(model);
    return NULL;
}


1110
static virCPUx86CompareResult
J
Jiri Denemark 已提交
1111 1112
x86ModelCompare(virCPUx86ModelPtr model1,
                virCPUx86ModelPtr model2)
J
Jiri Denemark 已提交
1113
{
1114
    virCPUx86CompareResult result = EQUAL;
1115 1116
    virCPUx86DataIterator iter1 = virCPUx86DataIteratorInit(&model1->data);
    virCPUx86DataIterator iter2 = virCPUx86DataIteratorInit(&model2->data);
1117 1118
    virCPUx86CPUID *cpuid1;
    virCPUx86CPUID *cpuid2;
J
Jiri Denemark 已提交
1119

J
Jiri Denemark 已提交
1120
    while ((cpuid1 = x86DataCpuidNext(&iter1))) {
1121
        virCPUx86CompareResult match = SUPERSET;
J
Jiri Denemark 已提交
1122

1123
        if ((cpuid2 = x86DataCpuid(&model2->data, cpuid1))) {
J
Jiri Denemark 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
            if (x86cpuidMatch(cpuid1, cpuid2))
                continue;
            else if (!x86cpuidMatchMasked(cpuid1, cpuid2))
                match = SUBSET;
        }

        if (result == EQUAL)
            result = match;
        else if (result != match)
            return UNRELATED;
    }

J
Jiri Denemark 已提交
1136
    while ((cpuid2 = x86DataCpuidNext(&iter2))) {
1137
        virCPUx86CompareResult match = SUBSET;
J
Jiri Denemark 已提交
1138

1139
        if ((cpuid1 = x86DataCpuid(&model1->data, cpuid2))) {
J
Jiri Denemark 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
            if (x86cpuidMatch(cpuid2, cpuid1))
                continue;
            else if (!x86cpuidMatchMasked(cpuid2, cpuid1))
                match = SUPERSET;
        }

        if (result == EQUAL)
            result = match;
        else if (result != match)
            return UNRELATED;
    }

    return result;
}


J
Jiri Denemark 已提交
1156 1157 1158
static virCPUx86ModelPtr
x86ModelParse(xmlXPathContextPtr ctxt,
              virCPUx86MapPtr map)
J
Jiri Denemark 已提交
1159 1160
{
    xmlNodePtr *nodes = NULL;
J
Jiri Denemark 已提交
1161
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
1162
    char *vendor = NULL;
1163
    size_t i;
J
Jiri Denemark 已提交
1164 1165
    int n;

J
Jiri Denemark 已提交
1166
    if (!(model = x86ModelNew()))
J
Jiri Denemark 已提交
1167
        goto error;
J
Jiri Denemark 已提交
1168

1169
    model->name = virXPathString("string(@name)", ctxt);
1170
    if (!model->name) {
1171 1172
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Missing CPU model name"));
J
Jiri Denemark 已提交
1173
        goto error;
J
Jiri Denemark 已提交
1174 1175
    }

1176
    if (virXPathNode("./model", ctxt)) {
J
Jiri Denemark 已提交
1177
        virCPUx86ModelPtr ancestor;
J
Jiri Denemark 已提交
1178 1179
        char *name;

1180
        name = virXPathString("string(./model/@name)", ctxt);
1181
        if (!name) {
1182 1183 1184
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Missing ancestor's name in CPU model %s"),
                           model->name);
J
Jiri Denemark 已提交
1185
            goto error;
J
Jiri Denemark 已提交
1186 1187
        }

1188
        if (!(ancestor = x86ModelFind(map, name))) {
1189 1190 1191
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Ancestor model %s not found for CPU model %s"),
                           name, model->name);
J
Jiri Denemark 已提交
1192
            VIR_FREE(name);
J
Jiri Denemark 已提交
1193
            goto error;
J
Jiri Denemark 已提交
1194 1195 1196 1197
        }

        VIR_FREE(name);

J
Jiri Denemark 已提交
1198
        model->vendor = ancestor->vendor;
1199
        if (x86DataCopy(&model->data, &ancestor->data) < 0)
J
Jiri Denemark 已提交
1200
            goto error;
J
Jiri Denemark 已提交
1201 1202
    }

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    if (virXPathBoolean("boolean(./signature)", ctxt)) {
        unsigned int sigFamily = 0;
        unsigned int sigModel = 0;
        int rc;

        rc = virXPathUInt("string(./signature/@family)", ctxt, &sigFamily);
        if (rc < 0 || sigFamily == 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid CPU signature family in model %s"),
                           model->name);
            goto cleanup;
        }

        rc = virXPathUInt("string(./signature/@model)", ctxt, &sigModel);
        if (rc < 0 || sigModel == 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid CPU signature model in model %s"),
                           model->name);
            goto cleanup;
        }

        model->signature = x86MakeSignature(sigFamily, sigModel);
    }

1227 1228 1229
    if (virXPathBoolean("boolean(./vendor)", ctxt)) {
        vendor = virXPathString("string(./vendor/@name)", ctxt);
        if (!vendor) {
1230 1231 1232
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid vendor element in CPU model %s"),
                           model->name);
J
Jiri Denemark 已提交
1233
            goto error;
1234 1235
        }

J
Jiri Denemark 已提交
1236
        if (!(model->vendor = x86VendorFind(map, vendor))) {
1237 1238 1239
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown vendor %s referenced by CPU model %s"),
                           vendor, model->name);
J
Jiri Denemark 已提交
1240
            goto error;
J
Jiri Denemark 已提交
1241 1242 1243
        }
    }

1244
    n = virXPathNodeSet("./feature", ctxt, &nodes);
J
Jiri Denemark 已提交
1245
    if (n < 0)
J
Jiri Denemark 已提交
1246
        goto error;
J
Jiri Denemark 已提交
1247 1248

    for (i = 0; i < n; i++) {
1249
        virCPUx86FeaturePtr feature;
J
Jiri Denemark 已提交
1250 1251
        char *name;

1252
        if (!(name = virXMLPropString(nodes[i], "name"))) {
1253 1254
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Missing feature name for CPU model %s"), model->name);
J
Jiri Denemark 已提交
1255
            goto error;
J
Jiri Denemark 已提交
1256 1257
        }

1258
        if (!(feature = x86FeatureFind(map, name))) {
1259 1260 1261
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Feature %s required by CPU model %s not found"),
                           name, model->name);
J
Jiri Denemark 已提交
1262
            VIR_FREE(name);
J
Jiri Denemark 已提交
1263
            goto error;
J
Jiri Denemark 已提交
1264 1265 1266
        }
        VIR_FREE(name);

1267
        if (x86DataAdd(&model->data, &feature->data))
J
Jiri Denemark 已提交
1268
            goto error;
J
Jiri Denemark 已提交
1269 1270
    }

J
Jiri Denemark 已提交
1271
 cleanup:
J
Jiri Denemark 已提交
1272
    VIR_FREE(vendor);
1273
    VIR_FREE(nodes);
J
Jiri Denemark 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    return model;

 error:
    x86ModelFree(model);
    model = NULL;
    goto cleanup;
}


static int
x86ModelsLoad(virCPUx86MapPtr map,
              xmlXPathContextPtr ctxt,
              xmlNodePtr *nodes,
              int n)
{
    virCPUx86ModelPtr model;
    size_t i;

    if (VIR_ALLOC_N(map->models, n) < 0)
        return -1;

    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
        if (!(model = x86ModelParse(ctxt, map)))
            return -1;
        map->models[map->nmodels++] = model;
    }

    return 0;
J
Jiri Denemark 已提交
1303 1304 1305 1306
}


static void
J
Jiri Denemark 已提交
1307
x86MapFree(virCPUx86MapPtr map)
J
Jiri Denemark 已提交
1308
{
1309 1310
    size_t i;

1311
    if (!map)
J
Jiri Denemark 已提交
1312 1313
        return;

1314 1315 1316
    for (i = 0; i < map->nfeatures; i++)
        x86FeatureFree(map->features[i]);
    VIR_FREE(map->features);
J
Jiri Denemark 已提交
1317

1318 1319 1320
    for (i = 0; i < map->nmodels; i++)
        x86ModelFree(map->models[i]);
    VIR_FREE(map->models);
J
Jiri Denemark 已提交
1321

1322 1323 1324
    for (i = 0; i < map->nvendors; i++)
        x86VendorFree(map->vendors[i]);
    VIR_FREE(map->vendors);
1325

1326 1327 1328 1329
    /* migrate_blockers only points to the features from map->features list,
     * which were already freed above
     */
    VIR_FREE(map->migrate_blockers);
1330

J
Jiri Denemark 已提交
1331 1332 1333 1334
    VIR_FREE(map);
}


J
Jiri Denemark 已提交
1335
static int
1336
x86MapLoadCallback(cpuMapElement element,
J
Jiri Denemark 已提交
1337
                   xmlXPathContextPtr ctxt,
J
Jiri Denemark 已提交
1338 1339
                   xmlNodePtr *nodes,
                   int n,
J
Jiri Denemark 已提交
1340 1341
                   void *data)
{
J
Jiri Denemark 已提交
1342
    virCPUx86MapPtr map = data;
J
Jiri Denemark 已提交
1343 1344 1345

    switch (element) {
    case CPU_MAP_ELEMENT_VENDOR:
J
Jiri Denemark 已提交
1346
        return x86VendorsLoad(map, ctxt, nodes, n);
J
Jiri Denemark 已提交
1347
    case CPU_MAP_ELEMENT_FEATURE:
J
Jiri Denemark 已提交
1348
        return x86FeaturesLoad(map, ctxt, nodes, n);
J
Jiri Denemark 已提交
1349
    case CPU_MAP_ELEMENT_MODEL:
J
Jiri Denemark 已提交
1350
        return x86ModelsLoad(map, ctxt, nodes, n);
J
Jiri Denemark 已提交
1351 1352 1353 1354 1355 1356 1357 1358
    case CPU_MAP_ELEMENT_LAST:
        break;
    }

    return 0;
}


J
Jiri Denemark 已提交
1359
static virCPUx86MapPtr
1360
virCPUx86LoadMap(void)
J
Jiri Denemark 已提交
1361
{
J
Jiri Denemark 已提交
1362
    virCPUx86MapPtr map;
J
Jiri Denemark 已提交
1363

1364
    if (VIR_ALLOC(map) < 0)
J
Jiri Denemark 已提交
1365 1366
        return NULL;

J
Jiri Denemark 已提交
1367
    if (cpuMapLoad("x86", x86MapLoadCallback, map) < 0)
J
Jiri Denemark 已提交
1368 1369 1370 1371
        goto error;

    return map;

1372
 error:
J
Jiri Denemark 已提交
1373 1374 1375 1376 1377
    x86MapFree(map);
    return NULL;
}


1378 1379 1380
int
virCPUx86MapOnceInit(void)
{
J
Jiri Denemark 已提交
1381
    if (!(cpuMap = virCPUx86LoadMap()))
1382 1383 1384 1385 1386 1387
        return -1;

    return 0;
}


J
Jiri Denemark 已提交
1388
static virCPUx86MapPtr
1389 1390 1391 1392 1393
virCPUx86GetMap(void)
{
    if (virCPUx86MapInitialize() < 0)
        return NULL;

J
Jiri Denemark 已提交
1394
    return cpuMap;
1395 1396 1397
}


1398
static char *
J
Jiri Denemark 已提交
1399
virCPUx86DataFormat(const virCPUData *data)
1400
{
1401
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(&data->data.x86);
1402
    virCPUx86CPUID *cpuid;
1403 1404 1405 1406 1407
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "<cpudata arch='x86'>\n");
    while ((cpuid = x86DataCpuidNext(&iter))) {
        virBufferAsprintf(&buf,
1408
                          "  <cpuid eax_in='0x%08x' ecx_in='0x%08x'"
1409 1410
                          " eax='0x%08x' ebx='0x%08x'"
                          " ecx='0x%08x' edx='0x%08x'/>\n",
1411
                          cpuid->eax_in, cpuid->ecx_in,
1412 1413 1414 1415
                          cpuid->eax, cpuid->ebx, cpuid->ecx, cpuid->edx);
    }
    virBufferAddLit(&buf, "</cpudata>\n");

1416
    if (virBufferCheckError(&buf) < 0)
1417 1418 1419 1420 1421 1422 1423
        return NULL;

    return virBufferContentAndReset(&buf);
}


static virCPUDataPtr
J
Jiri Denemark 已提交
1424
virCPUx86DataParse(xmlXPathContextPtr ctxt)
1425 1426 1427
{
    xmlNodePtr *nodes = NULL;
    virCPUDataPtr cpuData = NULL;
1428
    virCPUx86CPUID cpuid;
1429 1430 1431
    size_t i;
    int n;

1432
    n = virXPathNodeSet("/cpudata/cpuid", ctxt, &nodes);
J
Jiri Denemark 已提交
1433
    if (n <= 0) {
1434 1435
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no x86 CPU data found"));
1436
        goto error;
1437 1438
    }

1439 1440 1441
    if (!(cpuData = virCPUDataNew(VIR_ARCH_X86_64)))
        goto error;

1442 1443 1444 1445 1446
    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
        if (x86ParseCPUID(ctxt, &cpuid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse cpuid[%zu]"), i);
1447
            goto error;
1448
        }
1449 1450
        if (virCPUx86DataAddCPUID(&cpuData->data.x86, &cpuid) < 0)
            goto error;
1451 1452
    }

1453
 cleanup:
1454 1455
    VIR_FREE(nodes);
    return cpuData;
1456 1457 1458 1459 1460

 error:
    x86FreeCPUData(cpuData);
    cpuData = NULL;
    goto cleanup;
1461 1462 1463
}


1464 1465 1466
/* A helper macro to exit the cpu computation function without writing
 * redundant code:
 * MSG: error message
1467
 * CPU_DEF: a virCPUx86Data pointer with flags that are conflicting
1468 1469 1470 1471 1472 1473 1474
 * RET: return code to set
 *
 * This macro generates the error string outputs it into logs.
 */
#define virX86CpuIncompatible(MSG, CPU_DEF)                             \
        do {                                                            \
            char *flagsStr = NULL;                                      \
1475 1476 1477 1478
            if (!(flagsStr = x86FeatureNames(map, ", ", (CPU_DEF)))) {  \
                virReportOOMError();                                    \
                goto error;                                             \
            }                                                           \
1479 1480 1481
            if (message &&                                              \
                virAsprintf(message, "%s: %s", _(MSG), flagsStr) < 0) { \
                VIR_FREE(flagsStr);                                     \
1482
                goto error;                                             \
1483 1484 1485 1486 1487 1488
            }                                                           \
            VIR_DEBUG("%s: %s", MSG, flagsStr);                         \
            VIR_FREE(flagsStr);                                         \
            ret = VIR_CPU_COMPARE_INCOMPATIBLE;                         \
        } while (0)

1489

J
Jiri Denemark 已提交
1490 1491 1492
static virCPUCompareResult
x86Compute(virCPUDefPtr host,
           virCPUDefPtr cpu,
1493
           virCPUDataPtr *guest,
1494
           char **message)
J
Jiri Denemark 已提交
1495
{
J
Jiri Denemark 已提交
1496
    virCPUx86MapPtr map = NULL;
J
Jiri Denemark 已提交
1497 1498 1499 1500 1501 1502 1503 1504
    virCPUx86ModelPtr host_model = NULL;
    virCPUx86ModelPtr cpu_force = NULL;
    virCPUx86ModelPtr cpu_require = NULL;
    virCPUx86ModelPtr cpu_optional = NULL;
    virCPUx86ModelPtr cpu_disable = NULL;
    virCPUx86ModelPtr cpu_forbid = NULL;
    virCPUx86ModelPtr diff = NULL;
    virCPUx86ModelPtr guest_model = NULL;
1505
    virCPUDataPtr guestData = NULL;
J
Jiri Denemark 已提交
1506
    virCPUCompareResult ret;
1507
    virCPUx86CompareResult result;
J
Jiri Denemark 已提交
1508
    virArch arch;
1509
    size_t i;
J
Jiri Denemark 已提交
1510

1511
    if (cpu->arch != VIR_ARCH_NONE) {
J
Jiri Denemark 已提交
1512 1513 1514
        bool found = false;

        for (i = 0; i < ARRAY_CARDINALITY(archs); i++) {
1515
            if (archs[i] == cpu->arch) {
J
Jiri Denemark 已提交
1516 1517 1518 1519 1520
                found = true;
                break;
            }
        }

1521
        if (!found) {
1522 1523
            VIR_DEBUG("CPU arch %s does not match host arch",
                      virArchToString(cpu->arch));
1524 1525 1526
            if (message &&
                virAsprintf(message,
                            _("CPU arch %s does not match host arch"),
1527
                            virArchToString(cpu->arch)) < 0)
1528
                goto error;
J
Jiri Denemark 已提交
1529
            return VIR_CPU_COMPARE_INCOMPATIBLE;
1530
        }
J
Jiri Denemark 已提交
1531 1532 1533
        arch = cpu->arch;
    } else {
        arch = host->arch;
J
Jiri Denemark 已提交
1534 1535
    }

J
Jiri Denemark 已提交
1536 1537 1538 1539
    if (cpu->vendor &&
        (!host->vendor || STRNEQ(cpu->vendor, host->vendor))) {
        VIR_DEBUG("host CPU vendor does not match required CPU vendor %s",
                  cpu->vendor);
1540 1541 1542 1543 1544
        if (message &&
            virAsprintf(message,
                        _("host CPU vendor does not match required "
                          "CPU vendor %s"),
                        cpu->vendor) < 0)
1545
            goto error;
1546

J
Jiri Denemark 已提交
1547 1548 1549
        return VIR_CPU_COMPARE_INCOMPATIBLE;
    }

1550
    if (!(map = virCPUx86GetMap()) ||
J
Jiri Denemark 已提交
1551
        !(host_model = x86ModelFromCPU(host, map, -1)) ||
J
Jiri Denemark 已提交
1552 1553 1554 1555 1556
        !(cpu_force = x86ModelFromCPU(cpu, map, VIR_CPU_FEATURE_FORCE)) ||
        !(cpu_require = x86ModelFromCPU(cpu, map, VIR_CPU_FEATURE_REQUIRE)) ||
        !(cpu_optional = x86ModelFromCPU(cpu, map, VIR_CPU_FEATURE_OPTIONAL)) ||
        !(cpu_disable = x86ModelFromCPU(cpu, map, VIR_CPU_FEATURE_DISABLE)) ||
        !(cpu_forbid = x86ModelFromCPU(cpu, map, VIR_CPU_FEATURE_FORBID)))
J
Jiri Denemark 已提交
1557 1558
        goto error;

1559 1560
    x86DataIntersect(&cpu_forbid->data, &host_model->data);
    if (!x86DataIsEmpty(&cpu_forbid->data)) {
1561
        virX86CpuIncompatible(N_("Host CPU provides forbidden features"),
1562
                              &cpu_forbid->data);
1563
        goto cleanup;
J
Jiri Denemark 已提交
1564 1565
    }

1566 1567 1568
    /* first remove features that were inherited from the CPU model and were
     * explicitly forced, disabled, or made optional
     */
1569 1570 1571
    x86DataSubtract(&cpu_require->data, &cpu_force->data);
    x86DataSubtract(&cpu_require->data, &cpu_optional->data);
    x86DataSubtract(&cpu_require->data, &cpu_disable->data);
J
Jiri Denemark 已提交
1572 1573
    result = x86ModelCompare(host_model, cpu_require);
    if (result == SUBSET || result == UNRELATED) {
1574
        x86DataSubtract(&cpu_require->data, &host_model->data);
1575 1576
        virX86CpuIncompatible(N_("Host CPU does not provide required "
                                 "features"),
1577
                              &cpu_require->data);
1578
        goto cleanup;
J
Jiri Denemark 已提交
1579 1580 1581 1582
    }

    ret = VIR_CPU_COMPARE_IDENTICAL;

1583
    if (!(diff = x86ModelCopy(host_model)))
1584
        goto error;
J
Jiri Denemark 已提交
1585

1586 1587 1588 1589
    x86DataSubtract(&diff->data, &cpu_optional->data);
    x86DataSubtract(&diff->data, &cpu_require->data);
    x86DataSubtract(&diff->data, &cpu_disable->data);
    x86DataSubtract(&diff->data, &cpu_force->data);
J
Jiri Denemark 已提交
1590

1591
    if (!x86DataIsEmpty(&diff->data))
J
Jiri Denemark 已提交
1592
        ret = VIR_CPU_COMPARE_SUPERSET;
J
Jiri Denemark 已提交
1593 1594 1595 1596

    if (ret == VIR_CPU_COMPARE_SUPERSET
        && cpu->type == VIR_CPU_TYPE_GUEST
        && cpu->match == VIR_CPU_MATCH_STRICT) {
1597 1598
        virX86CpuIncompatible(N_("Host CPU does not strictly match guest CPU: "
                                 "Extra features"),
1599
                              &diff->data);
1600
        goto cleanup;
J
Jiri Denemark 已提交
1601 1602
    }

1603 1604
    if (guest) {
        if (!(guest_model = x86ModelCopy(host_model)))
1605
            goto error;
J
Jiri Denemark 已提交
1606

1607
        if (cpu->vendor && host_model->vendor &&
1608
            virCPUx86DataAddCPUID(&guest_model->data,
1609 1610 1611
                                  &host_model->vendor->cpuid) < 0)
            goto error;

1612 1613 1614
        if (x86DataAddSignature(&guest_model->data, host_model->signature) < 0)
            goto error;

J
Jiri Denemark 已提交
1615 1616
        if (cpu->type == VIR_CPU_TYPE_GUEST
            && cpu->match == VIR_CPU_MATCH_EXACT)
1617
            x86DataSubtract(&guest_model->data, &diff->data);
J
Jiri Denemark 已提交
1618

1619
        if (x86DataAdd(&guest_model->data, &cpu_force->data))
1620
            goto error;
J
Jiri Denemark 已提交
1621

1622
        x86DataSubtract(&guest_model->data, &cpu_disable->data);
J
Jiri Denemark 已提交
1623

1624 1625
        if (!(guestData = virCPUDataNew(arch)) ||
            x86DataCopy(&guestData->data.x86, &guest_model->data) < 0)
1626
            goto error;
1627 1628

        *guest = guestData;
J
Jiri Denemark 已提交
1629 1630
    }

1631
 cleanup:
J
Jiri Denemark 已提交
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    x86ModelFree(host_model);
    x86ModelFree(diff);
    x86ModelFree(cpu_force);
    x86ModelFree(cpu_require);
    x86ModelFree(cpu_optional);
    x86ModelFree(cpu_disable);
    x86ModelFree(cpu_forbid);
    x86ModelFree(guest_model);

    return ret;

1643
 error:
1644
    x86FreeCPUData(guestData);
J
Jiri Denemark 已提交
1645
    ret = VIR_CPU_COMPARE_ERROR;
1646
    goto cleanup;
J
Jiri Denemark 已提交
1647
}
1648
#undef virX86CpuIncompatible
J
Jiri Denemark 已提交
1649 1650 1651


static virCPUCompareResult
J
Jiri Denemark 已提交
1652 1653 1654
virCPUx86Compare(virCPUDefPtr host,
                 virCPUDefPtr cpu,
                 bool failIncompatible)
J
Jiri Denemark 已提交
1655
{
J
Jiri Denemark 已提交
1656 1657 1658
    virCPUCompareResult ret = VIR_CPU_COMPARE_ERROR;
    virCPUx86MapPtr map;
    virCPUx86ModelPtr model = NULL;
1659 1660
    char *message = NULL;

J
Jiri Denemark 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    if (!host || !host->model) {
        if (failIncompatible) {
            virReportError(VIR_ERR_CPU_INCOMPATIBLE, "%s",
                           _("unknown host CPU"));
        } else {
            VIR_WARN("unknown host CPU");
            ret = VIR_CPU_COMPARE_INCOMPATIBLE;
        }
        goto cleanup;
    }

1672 1673
    ret = x86Compute(host, cpu, NULL, &message);

J
Jiri Denemark 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    if (ret == VIR_CPU_COMPARE_INCOMPATIBLE) {
        bool noTSX = false;

        if (STREQ_NULLABLE(cpu->model, "Haswell") ||
            STREQ_NULLABLE(cpu->model, "Broadwell")) {
            if (!(map = virCPUx86GetMap()))
                goto cleanup;

            if (!(model = x86ModelFromCPU(cpu, map, -1)))
                goto cleanup;

            noTSX = !x86FeatureInData("hle", &model->data, map) ||
                    !x86FeatureInData("rtm", &model->data, map);
        }

        if (failIncompatible) {
            ret = VIR_CPU_COMPARE_ERROR;
            if (message) {
                if (noTSX) {
                    virReportError(VIR_ERR_CPU_INCOMPATIBLE,
                                   _("%s; try using '%s-noTSX' CPU model"),
                                   message, cpu->model);
                } else {
                    virReportError(VIR_ERR_CPU_INCOMPATIBLE, "%s", message);
                }
            } else {
                if (noTSX) {
                    virReportError(VIR_ERR_CPU_INCOMPATIBLE,
                                   _("try using '%s-noTSX' CPU model"),
                                   cpu->model);
                } else {
                    virReportError(VIR_ERR_CPU_INCOMPATIBLE, NULL);
                }
            }
1708 1709 1710
        }
    }

J
Jiri Denemark 已提交
1711 1712 1713
 cleanup:
    VIR_FREE(message);
    x86ModelFree(model);
1714
    return ret;
J
Jiri Denemark 已提交
1715 1716 1717
}


1718
/*
1719 1720
 * Checks whether a candidate model is a better fit for the CPU data than the
 * current model.
1721
 *
1722 1723 1724
 * Returns 0 if current is better,
 *         1 if candidate is better,
 *         2 if candidate is the best one (search should stop now).
1725 1726
 */
static int
1727 1728 1729
x86DecodeUseCandidate(virCPUx86ModelPtr current,
                      virCPUDefPtr cpuCurrent,
                      virCPUx86ModelPtr candidate,
1730
                      virCPUDefPtr cpuCandidate,
1731
                      uint32_t signature,
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
                      const char *preferred,
                      bool checkPolicy)
{
    if (checkPolicy) {
        size_t i;
        for (i = 0; i < cpuCandidate->nfeatures; i++) {
            if (cpuCandidate->features[i].policy == VIR_CPU_FEATURE_DISABLE)
                return 0;
            cpuCandidate->features[i].policy = -1;
        }
    }

    if (preferred &&
        STREQ(cpuCandidate->model, preferred))
        return 2;

    if (!cpuCurrent)
        return 1;

1751 1752 1753 1754 1755 1756 1757 1758 1759
    /* Ideally we want to select a model with family/model equal to
     * family/model of the real CPU. Once we found such model, we only
     * consider candidates with matching family/model.
     */
    if (signature &&
        current->signature == signature &&
        candidate->signature != signature)
        return 0;

1760 1761 1762
    if (cpuCurrent->nfeatures > cpuCandidate->nfeatures)
        return 1;

1763 1764 1765 1766 1767 1768 1769 1770
    /* Prefer a candidate with matching signature even though it would
     * result in longer list of features.
     */
    if (signature &&
        candidate->signature == signature &&
        current->signature != signature)
        return 1;

1771 1772 1773 1774
    return 0;
}


J
Jiri Denemark 已提交
1775 1776
static int
x86Decode(virCPUDefPtr cpu,
1777
          const virCPUx86Data *data,
1778
          const char **models,
1779
          unsigned int nmodels,
1780 1781
          const char *preferred,
          unsigned int flags)
J
Jiri Denemark 已提交
1782 1783
{
    int ret = -1;
J
Jiri Denemark 已提交
1784
    virCPUx86MapPtr map;
J
Jiri Denemark 已提交
1785
    virCPUx86ModelPtr candidate;
1786
    virCPUDefPtr cpuCandidate;
1787
    virCPUx86ModelPtr model = NULL;
1788
    virCPUDefPtr cpuModel = NULL;
1789 1790
    virCPUx86Data copy = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data features = VIR_CPU_X86_DATA_INIT;
J
Jiri Denemark 已提交
1791
    virCPUx86VendorPtr vendor;
1792
    uint32_t signature;
1793
    ssize_t i;
1794
    int rc;
J
Jiri Denemark 已提交
1795

1796 1797
    virCheckFlags(VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES |
                  VIR_CONNECT_BASELINE_CPU_MIGRATABLE, -1);
1798

1799
    if (!data || !(map = virCPUx86GetMap()))
J
Jiri Denemark 已提交
1800 1801
        return -1;

J
Jiri Denemark 已提交
1802
    vendor = x86DataToVendor(data, map);
1803
    signature = x86DataToSignature(data);
J
Jiri Denemark 已提交
1804

1805 1806 1807 1808 1809
    /* Walk through the CPU models in reverse order to check newest
     * models first.
     */
    for (i = map->nmodels - 1; i >= 0; i--) {
        candidate = map->models[i];
1810
        if (!virCPUModelIsAllowed(candidate->name, models, nmodels)) {
1811 1812
            if (preferred && STREQ(candidate->name, preferred)) {
                if (cpu->fallback != VIR_CPU_FALLBACK_ALLOW) {
1813 1814 1815
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("CPU model %s is not supported by hypervisor"),
                                   preferred);
J
Jiri Denemark 已提交
1816
                    goto cleanup;
1817 1818 1819 1820 1821 1822 1823 1824 1825
                } else {
                    VIR_WARN("Preferred CPU model %s not allowed by"
                             " hypervisor; closest supported model will be"
                             " used", preferred);
                }
            } else {
                VIR_DEBUG("CPU model %s not allowed by hypervisor; ignoring",
                          candidate->name);
            }
1826
            continue;
J
Jiri Denemark 已提交
1827 1828
        }

J
Jiri Denemark 已提交
1829 1830 1831 1832
        /* Both vendor and candidate->vendor are pointers to a single list of
         * known vendors stored in the map.
         */
        if (vendor && candidate->vendor && vendor != candidate->vendor) {
J
Jiri Denemark 已提交
1833
            VIR_DEBUG("CPU vendor %s of model %s differs from %s; ignoring",
J
Jiri Denemark 已提交
1834
                      candidate->vendor->name, candidate->name, vendor->name);
1835
            continue;
J
Jiri Denemark 已提交
1836 1837
        }

J
Jiri Denemark 已提交
1838 1839 1840 1841
        if (!(cpuCandidate = x86DataToCPU(data, candidate, map)))
            goto cleanup;
        cpuCandidate->type = cpu->type;

1842 1843 1844
        if ((rc = x86DecodeUseCandidate(model, cpuModel,
                                        candidate, cpuCandidate,
                                        signature, preferred,
1845
                                        cpu->type == VIR_CPU_TYPE_HOST))) {
1846 1847
            virCPUDefFree(cpuModel);
            cpuModel = cpuCandidate;
1848
            model = candidate;
1849 1850
            if (rc == 2)
                break;
1851
        } else {
1852
            virCPUDefFree(cpuCandidate);
1853
        }
J
Jiri Denemark 已提交
1854 1855
    }

1856
    if (!cpuModel) {
1857 1858
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Cannot find suitable CPU model for given data"));
J
Jiri Denemark 已提交
1859
        goto cleanup;
J
Jiri Denemark 已提交
1860 1861
    }

1862 1863 1864 1865
    /* Remove non-migratable features if requested
     * Note: this only works as long as no CPU model contains non-migratable
     * features directly */
    if (flags & VIR_CONNECT_BASELINE_CPU_MIGRATABLE) {
1866 1867 1868 1869 1870
        i = 0;
        while (i < cpuModel->nfeatures) {
            if (x86FeatureIsMigratable(cpuModel->features[i].name, map)) {
                i++;
            } else {
1871 1872 1873
                VIR_FREE(cpuModel->features[i].name);
                VIR_DELETE_ELEMENT_INPLACE(cpuModel->features, i,
                                           cpuModel->nfeatures);
1874 1875 1876 1877
            }
        }
    }

1878
    if (flags & VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES) {
1879
        if (x86DataCopy(&copy, &model->data) < 0 ||
1880
            x86DataFromCPUFeatures(&features, cpuModel, map) < 0)
J
Jiri Denemark 已提交
1881
            goto cleanup;
1882

1883
        x86DataSubtract(&copy, &features);
1884
        if (x86DataToCPUFeatures(cpuModel, VIR_CPU_FEATURE_REQUIRE,
1885
                                 &copy, map) < 0)
J
Jiri Denemark 已提交
1886
            goto cleanup;
1887 1888
    }

J
Jiri Denemark 已提交
1889 1890 1891
    if (vendor && VIR_STRDUP(cpu->vendor, vendor->name) < 0)
        goto cleanup;

1892 1893
    VIR_STEAL_PTR(cpu->model, cpuModel->model);
    VIR_STEAL_PTR(cpu->features, cpuModel->features);
1894
    cpu->nfeatures = cpuModel->nfeatures;
1895 1896 1897
    cpuModel->nfeatures = 0;
    cpu->nfeatures_max = cpuModel->nfeatures_max;
    cpuModel->nfeatures_max = 0;
J
Jiri Denemark 已提交
1898 1899 1900

    ret = 0;

J
Jiri Denemark 已提交
1901
 cleanup:
1902
    virCPUDefFree(cpuModel);
1903 1904
    virCPUx86DataClear(&copy);
    virCPUx86DataClear(&features);
J
Jiri Denemark 已提交
1905 1906 1907
    return ret;
}

1908 1909
static int
x86DecodeCPUData(virCPUDefPtr cpu,
1910
                 const virCPUData *data,
1911 1912
                 const char **models,
                 unsigned int nmodels,
1913 1914
                 const char *preferred,
                 unsigned int flags)
1915
{
1916
    return x86Decode(cpu, &data->data.x86, models, nmodels, preferred, flags);
1917
}
J
Jiri Denemark 已提交
1918

1919

1920 1921 1922
static int
x86EncodePolicy(virCPUx86Data *data,
                const virCPUDef *cpu,
J
Jiri Denemark 已提交
1923
                virCPUx86MapPtr map,
1924
                virCPUFeaturePolicy policy)
J
Jiri Denemark 已提交
1925
{
J
Jiri Denemark 已提交
1926
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
1927 1928

    if (!(model = x86ModelFromCPU(cpu, map, policy)))
1929
        return -1;
J
Jiri Denemark 已提交
1930

1931 1932 1933
    *data = model->data;
    model->data.len = 0;
    model->data.data = NULL;
J
Jiri Denemark 已提交
1934 1935
    x86ModelFree(model);

1936
    return 0;
J
Jiri Denemark 已提交
1937 1938 1939 1940
}


static int
J
Jiri Denemark 已提交
1941
x86Encode(virArch arch,
1942
          const virCPUDef *cpu,
1943 1944 1945 1946 1947 1948
          virCPUDataPtr *forced,
          virCPUDataPtr *required,
          virCPUDataPtr *optional,
          virCPUDataPtr *disabled,
          virCPUDataPtr *forbidden,
          virCPUDataPtr *vendor)
J
Jiri Denemark 已提交
1949
{
J
Jiri Denemark 已提交
1950
    virCPUx86MapPtr map = NULL;
1951 1952 1953 1954 1955 1956
    virCPUDataPtr data_forced = NULL;
    virCPUDataPtr data_required = NULL;
    virCPUDataPtr data_optional = NULL;
    virCPUDataPtr data_disabled = NULL;
    virCPUDataPtr data_forbidden = NULL;
    virCPUDataPtr data_vendor = NULL;
J
Jiri Denemark 已提交
1957

1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
    if (forced)
        *forced = NULL;
    if (required)
        *required = NULL;
    if (optional)
        *optional = NULL;
    if (disabled)
        *disabled = NULL;
    if (forbidden)
        *forbidden = NULL;
    if (vendor)
        *vendor = NULL;

1971
    if (!(map = virCPUx86GetMap()))
J
Jiri Denemark 已提交
1972 1973
        goto error;

1974
    if (forced &&
1975 1976 1977
        (!(data_forced = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_forced->data.x86, cpu, map,
                         VIR_CPU_FEATURE_FORCE) < 0))
1978
        goto error;
J
Jiri Denemark 已提交
1979

1980
    if (required &&
1981 1982 1983
        (!(data_required = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_required->data.x86, cpu, map,
                         VIR_CPU_FEATURE_REQUIRE) < 0))
1984
        goto error;
J
Jiri Denemark 已提交
1985

1986
    if (optional &&
1987 1988 1989
        (!(data_optional = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_optional->data.x86, cpu, map,
                         VIR_CPU_FEATURE_OPTIONAL) < 0))
1990
        goto error;
J
Jiri Denemark 已提交
1991

1992
    if (disabled &&
1993 1994 1995
        (!(data_disabled = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_disabled->data.x86, cpu, map,
                         VIR_CPU_FEATURE_DISABLE) < 0))
1996
        goto error;
J
Jiri Denemark 已提交
1997

1998
    if (forbidden &&
1999 2000 2001
        (!(data_forbidden = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_forbidden->data.x86, cpu, map,
                         VIR_CPU_FEATURE_FORBID) < 0))
2002
        goto error;
J
Jiri Denemark 已提交
2003

J
Jiri Denemark 已提交
2004
    if (vendor) {
2005
        virCPUx86VendorPtr v = NULL;
J
Jiri Denemark 已提交
2006 2007

        if (cpu->vendor && !(v = x86VendorFind(map, cpu->vendor))) {
2008 2009
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("CPU vendor %s not found"), cpu->vendor);
J
Jiri Denemark 已提交
2010 2011 2012
            goto error;
        }

2013
        if (!(data_vendor = virCPUDataNew(arch)))
J
Jiri Denemark 已提交
2014 2015
            goto error;

2016 2017 2018
        if (v && virCPUx86DataAddCPUID(&data_vendor->data.x86, &v->cpuid) < 0)
            goto error;
    }
J
Jiri Denemark 已提交
2019

2020
    if (forced)
2021
        *forced = data_forced;
2022
    if (required)
2023
        *required = data_required;
2024
    if (optional)
2025
        *optional = data_optional;
2026
    if (disabled)
2027
        *disabled = data_disabled;
2028
    if (forbidden)
2029
        *forbidden = data_forbidden;
2030
    if (vendor)
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
        *vendor = data_vendor;

    return 0;

 error:
    x86FreeCPUData(data_forced);
    x86FreeCPUData(data_required);
    x86FreeCPUData(data_optional);
    x86FreeCPUData(data_disabled);
    x86FreeCPUData(data_forbidden);
    x86FreeCPUData(data_vendor);
2042
    return -1;
J
Jiri Denemark 已提交
2043 2044 2045
}


P
Pavel Hrdina 已提交
2046
#if defined(__i386__) || defined(__x86_64__)
J
Jiri Denemark 已提交
2047
static inline void
2048
cpuidCall(virCPUx86CPUID *cpuid)
J
Jiri Denemark 已提交
2049
{
2050
# if __x86_64__
2051
    asm("xor %%ebx, %%ebx;" /* clear the other registers as some cpuid */
2052
        "xor %%edx, %%edx;" /* functions may use them as additional arguments */
2053
        "cpuid;"
J
Jiri Denemark 已提交
2054 2055 2056 2057
        : "=a" (cpuid->eax),
          "=b" (cpuid->ebx),
          "=c" (cpuid->ecx),
          "=d" (cpuid->edx)
2058 2059
        : "a" (cpuid->eax_in),
          "c" (cpuid->ecx_in));
2060
# else
J
Jiri Denemark 已提交
2061 2062 2063 2064
    /* we need to avoid direct use of ebx for CPUID output as it is used
     * for global offset table on i386 with -fPIC
     */
    asm("push %%ebx;"
2065
        "xor %%ebx, %%ebx;" /* clear the other registers as some cpuid */
2066
        "xor %%edx, %%edx;" /* functions may use them as additional arguments */
J
Jiri Denemark 已提交
2067 2068 2069 2070 2071 2072 2073
        "cpuid;"
        "mov %%ebx, %1;"
        "pop %%ebx;"
        : "=a" (cpuid->eax),
          "=r" (cpuid->ebx),
          "=c" (cpuid->ecx),
          "=d" (cpuid->edx)
2074 2075
        : "a" (cpuid->eax_in),
          "c" (cpuid->ecx_in)
J
Jiri Denemark 已提交
2076
        : "cc");
2077
# endif
J
Jiri Denemark 已提交
2078 2079 2080
}


2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
/* Leaf 0x04: deterministic cache parameters
 *
 * Sub leaf n+1 is invalid if eax[4:0] in sub leaf n equals 0.
 */
static int
cpuidSetLeaf4(virCPUx86Data *data,
              virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = *subLeaf0;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    while (cpuid.eax & 0x1f) {
        cpuid.ecx_in++;
        cpuidCall(&cpuid);
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
    }
    return 0;
}


/* Leaf 0x07: structured extended feature flags enumeration
 *
 * Sub leaf n is invalid if n > eax in sub leaf 0.
 */
static int
cpuidSetLeaf7(virCPUx86Data *data,
              virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = { .eax_in = 0x7 };
    uint32_t sub;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    for (sub = 1; sub <= subLeaf0->eax; sub++) {
        cpuid.ecx_in = sub;
        cpuidCall(&cpuid);
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
    }
    return 0;
}


/* Leaf 0x0b: extended topology enumeration
 *
 * Sub leaf n is invalid if it returns 0 in ecx[15:8].
 * Sub leaf n+1 is invalid if sub leaf n is invalid.
 * Some output values do not depend on ecx, thus sub leaf 0 provides
 * meaningful data even if it was (theoretically) considered invalid.
 */
static int
cpuidSetLeafB(virCPUx86Data *data,
              virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = *subLeaf0;

    while (cpuid.ecx & 0xff00) {
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
        cpuid.ecx_in++;
        cpuidCall(&cpuid);
    }
    return 0;
}


/* Leaf 0x0d: processor extended state enumeration
 *
 * Sub leaves 0 and 1 are valid.
 * Sub leaf n (2 <= n < 32) is invalid if eax[n] from sub leaf 0 is not set
 * and ecx[n] from sub leaf 1 is not set.
 * Sub leaf n (32 <= n < 64) is invalid if edx[n-32] from sub leaf 0 is not set
 * and edx[n-32] from sub leaf 1 is not set.
 */
static int
cpuidSetLeafD(virCPUx86Data *data,
              virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = { .eax_in = 0xd };
    virCPUx86CPUID sub0;
    virCPUx86CPUID sub1;
    uint32_t sub;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    cpuid.ecx_in = 1;
    cpuidCall(&cpuid);
    if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
        return -1;

    sub0 = *subLeaf0;
    sub1 = cpuid;
    for (sub = 2; sub < 64; sub++) {
        if (sub < 32 &&
            !(sub0.eax & (1 << sub)) &&
            !(sub1.ecx & (1 << sub)))
            continue;
        if (sub >= 32 &&
            !(sub0.edx & (1 << (sub - 32))) &&
            !(sub1.edx & (1 << (sub - 32))))
            continue;

        cpuid.ecx_in = sub;
        cpuidCall(&cpuid);
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
    }
    return 0;
}


/* Leaf 0x0f: L3 cached RDT monitoring capability enumeration
 * Leaf 0x10: RDT allocation enumeration
 *
 * res reports valid resource identification (ResID) starting at bit 1.
 * Values associated with each valid ResID are reported by ResID sub leaf.
 *
 * 0x0f: Sub leaf n is valid if edx[n] (= res[ResID]) from sub leaf 0 is set.
 * 0x10: Sub leaf n is valid if ebx[n] (= res[ResID]) from sub leaf 0 is set.
 */
static int
cpuidSetLeafResID(virCPUx86Data *data,
                  virCPUx86CPUID *subLeaf0,
                  uint32_t res)
{
    virCPUx86CPUID cpuid = { .eax_in = subLeaf0->eax_in };
    uint32_t sub;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    for (sub = 1; sub < 32; sub++) {
        if (!(res & (1 << sub)))
            continue;
        cpuid.ecx_in = sub;
        cpuidCall(&cpuid);
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
    }
    return 0;
}


/* Leaf 0x12: SGX capability enumeration
 *
 * Sub leaves 0 and 1 is supported if ebx[2] from leaf 0x7 (SGX) is set.
 * Sub leaves n >= 2 are valid as long as eax[3:0] != 0.
 */
static int
cpuidSetLeaf12(virCPUx86Data *data,
               virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = { .eax_in = 0x7 };
    virCPUx86CPUID *cpuid7;

    if (!(cpuid7 = x86DataCpuid(data, &cpuid)) ||
        !(cpuid7->ebx & (1 << 2)))
        return 0;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    cpuid.eax_in = 0x12;
    cpuid.ecx_in = 1;
    cpuidCall(&cpuid);
    if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
        return -1;

    cpuid.ecx_in = 2;
    cpuidCall(&cpuid);
    while (cpuid.eax & 0xf) {
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
        cpuid.ecx_in++;
        cpuidCall(&cpuid);
    }
    return 0;
}


/* Leaf 0x14: processor trace enumeration
 *
 * Sub leaf 0 reports the maximum supported sub leaf in eax.
 */
static int
cpuidSetLeaf14(virCPUx86Data *data,
               virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = { .eax_in = 0x14 };
    uint32_t sub;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    for (sub = 1; sub <= subLeaf0->eax; sub++) {
        cpuid.ecx_in = sub;
        cpuidCall(&cpuid);
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
    }
    return 0;
}


/* Leaf 0x17: SOC Vendor
 *
 * Sub leaf 0 is valid if eax >= 3.
 * Sub leaf 0 reports the maximum supported sub leaf in eax.
 */
static int
cpuidSetLeaf17(virCPUx86Data *data,
               virCPUx86CPUID *subLeaf0)
{
    virCPUx86CPUID cpuid = { .eax_in = 0x17 };
    uint32_t sub;

    if (subLeaf0->eax < 3)
        return 0;

    if (virCPUx86DataAddCPUID(data, subLeaf0) < 0)
        return -1;

    for (sub = 1; sub <= subLeaf0->eax; sub++) {
        cpuid.ecx_in = sub;
        cpuidCall(&cpuid);
        if (virCPUx86DataAddCPUID(data, &cpuid) < 0)
            return -1;
    }
    return 0;
}


J
Jiri Denemark 已提交
2318
static int
2319
cpuidSet(uint32_t base, virCPUx86Data *data)
J
Jiri Denemark 已提交
2320
{
2321
    int rc;
J
Jiri Denemark 已提交
2322
    uint32_t max;
2323
    uint32_t leaf;
2324
    virCPUx86CPUID cpuid = { .eax_in = base };
J
Jiri Denemark 已提交
2325 2326

    cpuidCall(&cpuid);
2327
    max = cpuid.eax;
J
Jiri Denemark 已提交
2328

2329 2330
    for (leaf = base; leaf <= max; leaf++) {
        cpuid.eax_in = leaf;
2331
        cpuid.ecx_in = 0;
J
Jiri Denemark 已提交
2332
        cpuidCall(&cpuid);
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358

        /* Handle CPUID leaves that depend on previously queried bits or
         * which provide additional sub leaves for ecx_in > 0
         */
        if (leaf == 0x4)
            rc = cpuidSetLeaf4(data, &cpuid);
        else if (leaf == 0x7)
            rc = cpuidSetLeaf7(data, &cpuid);
        else if (leaf == 0xb)
            rc = cpuidSetLeafB(data, &cpuid);
        else if (leaf == 0xd)
            rc = cpuidSetLeafD(data, &cpuid);
        else if (leaf == 0xf)
            rc = cpuidSetLeafResID(data, &cpuid, cpuid.edx);
        else if (leaf == 0x10)
            rc = cpuidSetLeafResID(data, &cpuid, cpuid.ebx);
        else if (leaf == 0x12)
            rc = cpuidSetLeaf12(data, &cpuid);
        else if (leaf == 0x14)
            rc = cpuidSetLeaf14(data, &cpuid);
        else if (leaf == 0x17)
            rc = cpuidSetLeaf17(data, &cpuid);
        else
            rc = virCPUx86DataAddCPUID(data, &cpuid);

        if (rc < 0)
2359
            return -1;
J
Jiri Denemark 已提交
2360 2361
    }

2362
    return 0;
J
Jiri Denemark 已提交
2363 2364 2365
}


2366
static virCPUDataPtr
2367
x86NodeData(virArch arch)
J
Jiri Denemark 已提交
2368
{
2369
    virCPUDataPtr cpuData = NULL;
J
Jiri Denemark 已提交
2370

2371
    if (!(cpuData = virCPUDataNew(arch)))
J
Jiri Denemark 已提交
2372 2373
        goto error;

2374
    if (cpuidSet(CPUX86_BASIC, &cpuData->data.x86) < 0)
J
Jiri Denemark 已提交
2375 2376
        goto error;

2377
    if (cpuidSet(CPUX86_EXTENDED, &cpuData->data.x86) < 0)
2378 2379 2380
        goto error;

    return cpuData;
J
Jiri Denemark 已提交
2381

2382
 error:
2383
    x86FreeCPUData(cpuData);
J
Jiri Denemark 已提交
2384 2385 2386 2387 2388
    return NULL;
}
#endif


2389 2390 2391 2392
static virCPUDefPtr
x86Baseline(virCPUDefPtr *cpus,
            unsigned int ncpus,
            const char **models,
2393 2394
            unsigned int nmodels,
            unsigned int flags)
2395
{
J
Jiri Denemark 已提交
2396
    virCPUx86MapPtr map = NULL;
J
Jiri Denemark 已提交
2397
    virCPUx86ModelPtr base_model = NULL;
2398
    virCPUDefPtr cpu = NULL;
2399
    size_t i;
2400
    virCPUx86VendorPtr vendor = NULL;
J
Jiri Denemark 已提交
2401
    virCPUx86ModelPtr model = NULL;
2402
    bool outputVendor = true;
2403 2404
    const char *modelName;
    bool matchingNames = true;
2405

2406 2407 2408
    virCheckFlags(VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES |
                  VIR_CONNECT_BASELINE_CPU_MIGRATABLE, NULL);

2409
    if (!(map = virCPUx86GetMap()))
2410 2411
        goto error;

2412
    if (!(base_model = x86ModelFromCPU(cpus[0], map, VIR_CPU_FEATURE_REQUIRE)))
2413 2414
        goto error;

2415
    if (VIR_ALLOC(cpu) < 0)
2416
        goto error;
2417 2418

    cpu->arch = cpus[0]->arch;
2419 2420
    cpu->type = VIR_CPU_TYPE_GUEST;
    cpu->match = VIR_CPU_MATCH_EXACT;
2421

2422
    if (!cpus[0]->vendor) {
2423
        outputVendor = false;
2424
    } else if (!(vendor = x86VendorFind(map, cpus[0]->vendor))) {
2425 2426
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unknown CPU vendor %s"), cpus[0]->vendor);
J
Jiri Denemark 已提交
2427 2428 2429
        goto error;
    }

2430
    modelName = cpus[0]->model;
2431
    for (i = 1; i < ncpus; i++) {
J
Jiri Denemark 已提交
2432 2433
        const char *vn = NULL;

2434 2435 2436 2437 2438 2439 2440 2441 2442
        if (matchingNames && cpus[i]->model) {
            if (!modelName) {
                modelName = cpus[i]->model;
            } else if (STRNEQ(modelName, cpus[i]->model)) {
                modelName = NULL;
                matchingNames = false;
            }
        }

2443
        if (!(model = x86ModelFromCPU(cpus[i], map, VIR_CPU_FEATURE_REQUIRE)))
2444 2445
            goto error;

J
Jiri Denemark 已提交
2446 2447
        if (cpus[i]->vendor && model->vendor &&
            STRNEQ(cpus[i]->vendor, model->vendor->name)) {
2448 2449 2450
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("CPU vendor %s of model %s differs from vendor %s"),
                           model->vendor->name, model->name, cpus[i]->vendor);
J
Jiri Denemark 已提交
2451 2452 2453
            goto error;
        }

2454
        if (cpus[i]->vendor) {
J
Jiri Denemark 已提交
2455
            vn = cpus[i]->vendor;
2456
        } else {
2457 2458 2459 2460
            outputVendor = false;
            if (model->vendor)
                vn = model->vendor->name;
        }
J
Jiri Denemark 已提交
2461 2462 2463 2464

        if (vn) {
            if (!vendor) {
                if (!(vendor = x86VendorFind(map, vn))) {
2465 2466
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("Unknown CPU vendor %s"), vn);
J
Jiri Denemark 已提交
2467 2468 2469
                    goto error;
                }
            } else if (STRNEQ(vendor->name, vn)) {
2470 2471
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("CPU vendors do not match"));
J
Jiri Denemark 已提交
2472 2473 2474 2475
                goto error;
            }
        }

2476
        x86DataIntersect(&base_model->data, &model->data);
2477
        x86ModelFree(model);
J
Jiri Denemark 已提交
2478
        model = NULL;
2479 2480
    }

2481
    if (x86DataIsEmpty(&base_model->data)) {
2482 2483
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("CPUs are incompatible"));
2484 2485 2486
        goto error;
    }

2487
    if (vendor && virCPUx86DataAddCPUID(&base_model->data, &vendor->cpuid) < 0)
2488
        goto error;
J
Jiri Denemark 已提交
2489

2490
    if (x86Decode(cpu, &base_model->data, models, nmodels, modelName, flags) < 0)
2491 2492
        goto error;

2493 2494 2495
    if (STREQ_NULLABLE(cpu->model, modelName))
        cpu->fallback = VIR_CPU_FALLBACK_FORBID;

2496 2497 2498
    if (!outputVendor)
        VIR_FREE(cpu->vendor);

2499 2500
    cpu->arch = VIR_ARCH_NONE;

2501
 cleanup:
2502 2503 2504 2505
    x86ModelFree(base_model);

    return cpu;

2506
 error:
J
Jiri Denemark 已提交
2507
    x86ModelFree(model);
2508 2509 2510 2511 2512 2513
    virCPUDefFree(cpu);
    cpu = NULL;
    goto cleanup;
}


2514
static int
J
Jiri Denemark 已提交
2515 2516 2517
x86UpdateHostModel(virCPUDefPtr guest,
                   const virCPUDef *host,
                   virCPUx86MapPtr map)
2518
{
J
Jiri Denemark 已提交
2519
    virCPUDefPtr updated = NULL;
2520
    size_t i;
J
Jiri Denemark 已提交
2521
    int ret = -1;
2522

J
Jiri Denemark 已提交
2523
    if (!(updated = virCPUDefCopyWithoutModel(host)))
2524 2525
        goto cleanup;

J
Jiri Denemark 已提交
2526 2527 2528
    /* Remove non-migratable features by default */
    updated->type = VIR_CPU_TYPE_GUEST;
    updated->mode = VIR_CPU_MODE_CUSTOM;
2529 2530
    if (virCPUDefCopyModelFilter(updated, host, true,
                                 x86FeatureIsMigratable, map) < 0)
J
Jiri Denemark 已提交
2531
        goto cleanup;
2532

J
Jiri Denemark 已提交
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
    if (guest->vendor_id) {
        VIR_FREE(updated->vendor_id);
        if (VIR_STRDUP(updated->vendor_id, guest->vendor_id) < 0)
            goto cleanup;
    }

    for (i = 0; i < guest->nfeatures; i++) {
        if (virCPUDefUpdateFeature(updated,
                                   guest->features[i].name,
                                   guest->features[i].policy) < 0)
2543 2544 2545
            goto cleanup;
    }

2546 2547
    virCPUDefStealModel(guest, updated,
                        guest->mode == VIR_CPU_MODE_CUSTOM);
J
Jiri Denemark 已提交
2548 2549
    guest->mode = VIR_CPU_MODE_CUSTOM;
    guest->match = VIR_CPU_MATCH_EXACT;
2550 2551
    ret = 0;

2552
 cleanup:
J
Jiri Denemark 已提交
2553
    virCPUDefFree(updated);
2554 2555 2556
    return ret;
}

2557 2558

static int
J
Jiri Denemark 已提交
2559 2560
virCPUx86Update(virCPUDefPtr guest,
                const virCPUDef *host)
2561
{
J
Jiri Denemark 已提交
2562
    virCPUx86ModelPtr model = NULL;
J
Jiri Denemark 已提交
2563
    virCPUx86MapPtr map;
2564
    int ret = -1;
J
Jiri Denemark 已提交
2565
    size_t i;
2566

J
Jiri Denemark 已提交
2567 2568 2569 2570 2571
    if (!host) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unknown host CPU model"));
        return -1;
    }
2572

J
Jiri Denemark 已提交
2573 2574
    if (!(map = virCPUx86GetMap()))
        return -1;
2575

J
Jiri Denemark 已提交
2576
    if (!(model = x86ModelFromCPU(host, map, -1)))
2577
        goto cleanup;
2578

J
Jiri Denemark 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
    for (i = 0; i < guest->nfeatures; i++) {
        if (guest->features[i].policy == VIR_CPU_FEATURE_OPTIONAL) {
            int supported = x86FeatureInData(guest->features[i].name,
                                             &model->data, map);
            if (supported < 0)
                goto cleanup;
            else if (supported)
                guest->features[i].policy = VIR_CPU_FEATURE_REQUIRE;
            else
                guest->features[i].policy = VIR_CPU_FEATURE_DISABLE;
2589 2590
        }
    }
2591

J
Jiri Denemark 已提交
2592 2593 2594 2595 2596
    if (guest->mode == VIR_CPU_MODE_HOST_MODEL ||
        guest->match == VIR_CPU_MATCH_MINIMUM)
        ret = x86UpdateHostModel(guest, host, map);
    else
        ret = 0;
2597 2598

 cleanup:
J
Jiri Denemark 已提交
2599
    x86ModelFree(model);
2600
    return ret;
2601 2602 2603
}


2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
static int
virCPUx86CheckFeature(const virCPUDef *cpu,
                      const char *name)
{
    int ret = -1;
    virCPUx86MapPtr map;
    virCPUx86ModelPtr model = NULL;

    if (!(map = virCPUx86GetMap()))
        return -1;

    if (!(model = x86ModelFromCPU(cpu, map, -1)))
        goto cleanup;

    ret = x86FeatureInData(name, &model->data, map);

 cleanup:
    x86ModelFree(model);
    return ret;
}


2626
static int
2627 2628
virCPUx86DataCheckFeature(const virCPUData *data,
                          const char *name)
D
Daniel P. Berrange 已提交
2629
{
J
Jiri Denemark 已提交
2630
    virCPUx86MapPtr map;
D
Daniel P. Berrange 已提交
2631

2632
    if (!(map = virCPUx86GetMap()))
D
Daniel P. Berrange 已提交
2633 2634
        return -1;

J
Jiri Denemark 已提交
2635
    return x86FeatureInData(name, &data->data.x86, map);
D
Daniel P. Berrange 已提交
2636
}
2637

2638
static int
J
Jiri Denemark 已提交
2639
virCPUx86GetModels(char ***models)
2640
{
J
Jiri Denemark 已提交
2641
    virCPUx86MapPtr map;
2642
    size_t i;
2643 2644 2645 2646

    if (!(map = virCPUx86GetMap()))
        return -1;

2647 2648 2649
    if (models) {
        if (VIR_ALLOC_N(*models, map->nmodels + 1) < 0)
            goto error;
2650

2651 2652
        for (i = 0; i < map->nmodels; i++) {
            if (VIR_STRDUP((*models)[i], map->models[i]->name) < 0)
2653 2654
                goto error;
        }
2655 2656
    }

2657
    return map->nmodels;
2658 2659

 error:
2660
    if (models) {
2661
        virStringListFree(*models);
2662 2663
        *models = NULL;
    }
2664 2665 2666
    return -1;
}

2667

J
Jiri Denemark 已提交
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
static int
virCPUx86Translate(virCPUDefPtr cpu,
                   const char **models,
                   unsigned int nmodels)
{
    virCPUDefPtr translated = NULL;
    virCPUx86MapPtr map;
    virCPUx86ModelPtr model = NULL;
    size_t i;
    int ret = -1;

    if (!(map = virCPUx86GetMap()))
        goto cleanup;

    if (!(model = x86ModelFromCPU(cpu, map, -1)))
        goto cleanup;

    if (model->vendor &&
        virCPUx86DataAddCPUID(&model->data, &model->vendor->cpuid) < 0)
        goto cleanup;

    if (x86DataAddSignature(&model->data, model->signature) < 0)
        goto cleanup;

    if (!(translated = virCPUDefCopyWithoutModel(cpu)))
        goto cleanup;

    if (x86Decode(translated, &model->data, models, nmodels, NULL, 0) < 0)
        goto cleanup;

    for (i = 0; i < cpu->nfeatures; i++) {
        virCPUFeatureDefPtr f = cpu->features + i;
        if (virCPUDefUpdateFeature(translated, f->name, f->policy) < 0)
            goto cleanup;
    }

2704
    virCPUDefStealModel(cpu, translated, true);
J
Jiri Denemark 已提交
2705 2706 2707 2708 2709 2710 2711 2712 2713
    ret = 0;

 cleanup:
    virCPUDefFree(translated);
    x86ModelFree(model);
    return ret;
}


J
Jiri Denemark 已提交
2714 2715 2716 2717
struct cpuArchDriver cpuDriverX86 = {
    .name = "x86",
    .arch = archs,
    .narch = ARRAY_CARDINALITY(archs),
J
Jiri Denemark 已提交
2718
    .compare    = virCPUx86Compare,
2719
    .decode     = x86DecodeCPUData,
J
Jiri Denemark 已提交
2720
    .encode     = x86Encode,
2721
    .free       = x86FreeCPUData,
P
Pavel Hrdina 已提交
2722
#if defined(__i386__) || defined(__x86_64__)
J
Jiri Denemark 已提交
2723 2724 2725 2726
    .nodeData   = x86NodeData,
#else
    .nodeData   = NULL,
#endif
2727
    .baseline   = x86Baseline,
J
Jiri Denemark 已提交
2728
    .update     = virCPUx86Update,
2729
    .checkFeature = virCPUx86CheckFeature,
2730
    .dataCheckFeature = virCPUx86DataCheckFeature,
J
Jiri Denemark 已提交
2731
    .dataFormat = virCPUx86DataFormat,
J
Jiri Denemark 已提交
2732
    .dataParse  = virCPUx86DataParse,
J
Jiri Denemark 已提交
2733
    .getModels  = virCPUx86GetModels,
J
Jiri Denemark 已提交
2734
    .translate  = virCPUx86Translate,
J
Jiri Denemark 已提交
2735
};