cpu_x86.c 81.8 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
 */

#include <config.h>


24
#include "virlog.h"
25
#include "viralloc.h"
J
Jiri Denemark 已提交
26 27 28
#include "cpu.h"
#include "cpu_map.h"
#include "cpu_x86.h"
29
#include "virbuffer.h"
E
Eric Blake 已提交
30
#include "virendian.h"
31
#include "virstring.h"
32
#include "virhostcpu.h"
J
Jiri Denemark 已提交
33 34 35

#define VIR_FROM_THIS VIR_FROM_CPU

36 37
VIR_LOG_INIT("cpu.cpu_x86");

J
Jiri Denemark 已提交
38 39
#define VENDOR_STRING_LENGTH    12

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

42 43 44
typedef struct _virCPUx86Vendor virCPUx86Vendor;
typedef virCPUx86Vendor *virCPUx86VendorPtr;
struct _virCPUx86Vendor {
J
Jiri Denemark 已提交
45
    char *name;
46
    virCPUx86DataItem data;
J
Jiri Denemark 已提交
47 48
};

49 50 51
typedef struct _virCPUx86Feature virCPUx86Feature;
typedef virCPUx86Feature *virCPUx86FeaturePtr;
struct _virCPUx86Feature {
J
Jiri Denemark 已提交
52
    char *name;
53
    virCPUx86Data data;
J
Jiri Denemark 已提交
54
    bool migratable;
J
Jiri Denemark 已提交
55 56
};

57

58 59
#define CPUID(...) { .cpuid = {__VA_ARGS__} }

60
#define KVM_FEATURE_DEF(Name, Eax_in, Eax) \
61 62
    static virCPUx86DataItem Name ## _data[] = { \
        CPUID(.eax_in = Eax_in, .eax = Eax), \
63 64
    }

65 66 67 68
#define KVM_FEATURE(Name) \
    { \
        .name = (char *) Name, \
        .data = { \
69 70
            .len = ARRAY_CARDINALITY(Name ## _data), \
            .items = Name ## _data, \
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
    }

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);
100
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_SPINLOCKS,
101 102 103 104 105 106 107
                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);
108 109
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_FREQUENCIES,
                0x40000003, 0x00000800);
110 111
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_REENLIGHTENMENT,
                0x40000003, 0x00002000);
112 113
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_TLBFLUSH,
                0x40000004, 0x00000004);
114 115
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_IPI,
                0x40000004, 0x00000400);
116 117
KVM_FEATURE_DEF(VIR_CPU_x86_KVM_HV_EVMCS,
                0x40000004, 0x00004000);
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

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),
134
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_SPINLOCKS),
135 136 137
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_VAPIC),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_VPINDEX),
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_RESET),
138
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_FREQUENCIES),
139
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_REENLIGHTENMENT),
140
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_TLBFLUSH),
141
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_IPI),
142
    KVM_FEATURE(VIR_CPU_x86_KVM_HV_EVMCS),
143 144
};

J
Jiri Denemark 已提交
145 146 147
typedef struct _virCPUx86Model virCPUx86Model;
typedef virCPUx86Model *virCPUx86ModelPtr;
struct _virCPUx86Model {
J
Jiri Denemark 已提交
148
    char *name;
149
    virCPUx86VendorPtr vendor;
150 151
    size_t nsignatures;
    uint32_t *signatures;
152
    virCPUx86Data data;
J
Jiri Denemark 已提交
153 154
};

J
Jiri Denemark 已提交
155 156 157
typedef struct _virCPUx86Map virCPUx86Map;
typedef virCPUx86Map *virCPUx86MapPtr;
struct _virCPUx86Map {
158 159
    size_t nvendors;
    virCPUx86VendorPtr *vendors;
160 161
    size_t nfeatures;
    virCPUx86FeaturePtr *features;
162 163
    size_t nmodels;
    virCPUx86ModelPtr *models;
164 165
    size_t nblockers;
    virCPUx86FeaturePtr *migrate_blockers;
J
Jiri Denemark 已提交
166 167
};

J
Jiri Denemark 已提交
168
static virCPUx86MapPtr cpuMap;
169

170 171
int virCPUx86DriverOnceInit(void);
VIR_ONCE_GLOBAL_INIT(virCPUx86Driver);
172

J
Jiri Denemark 已提交
173

174
typedef enum {
J
Jiri Denemark 已提交
175 176 177 178
    SUBSET,
    EQUAL,
    SUPERSET,
    UNRELATED
179
} virCPUx86CompareResult;
J
Jiri Denemark 已提交
180 181


182 183 184
typedef struct _virCPUx86DataIterator virCPUx86DataIterator;
typedef virCPUx86DataIterator *virCPUx86DataIteratorPtr;
struct _virCPUx86DataIterator {
185
    const virCPUx86Data *data;
J
Jiri Denemark 已提交
186 187
    int pos;
};
J
Jiri Denemark 已提交
188 189


190
#define virCPUx86DataIteratorInit(data) \
191
    { data, -1 }
J
Jiri Denemark 已提交
192 193


194
static bool
195 196
virCPUx86DataItemMatch(const virCPUx86DataItem *item1,
                       const virCPUx86DataItem *item2)
J
Jiri Denemark 已提交
197
{
198 199 200 201
    return (item1->cpuid.eax == item2->cpuid.eax &&
            item1->cpuid.ebx == item2->cpuid.ebx &&
            item1->cpuid.ecx == item2->cpuid.ecx &&
            item1->cpuid.edx == item2->cpuid.edx);
J
Jiri Denemark 已提交
202 203 204
}


205
static bool
206 207
virCPUx86DataItemMatchMasked(const virCPUx86DataItem *item,
                             const virCPUx86DataItem *mask)
J
Jiri Denemark 已提交
208
{
209 210 211 212
    return ((item->cpuid.eax & mask->cpuid.eax) == mask->cpuid.eax &&
            (item->cpuid.ebx & mask->cpuid.ebx) == mask->cpuid.ebx &&
            (item->cpuid.ecx & mask->cpuid.ecx) == mask->cpuid.ecx &&
            (item->cpuid.edx & mask->cpuid.edx) == mask->cpuid.edx);
J
Jiri Denemark 已提交
213 214 215
}


J
Jiri Denemark 已提交
216
static void
217 218
virCPUx86DataItemSetBits(virCPUx86DataItemPtr item,
                         const virCPUx86DataItem *mask)
J
Jiri Denemark 已提交
219
{
220 221 222
    if (!mask)
        return;

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


J
Jiri Denemark 已提交
230
static void
231 232
virCPUx86DataItemClearBits(virCPUx86DataItemPtr item,
                           const virCPUx86DataItem *mask)
J
Jiri Denemark 已提交
233
{
234 235 236
    if (!mask)
        return;

237 238 239 240
    item->cpuid.eax &= ~mask->cpuid.eax;
    item->cpuid.ebx &= ~mask->cpuid.ebx;
    item->cpuid.ecx &= ~mask->cpuid.ecx;
    item->cpuid.edx &= ~mask->cpuid.edx;
J
Jiri Denemark 已提交
241 242 243
}


J
Jiri Denemark 已提交
244
static void
245 246
virCPUx86DataItemAndBits(virCPUx86DataItemPtr item,
                         const virCPUx86DataItem *mask)
247
{
248 249 250
    if (!mask)
        return;

251 252 253 254
    item->cpuid.eax &= mask->cpuid.eax;
    item->cpuid.ebx &= mask->cpuid.ebx;
    item->cpuid.ecx &= mask->cpuid.ecx;
    item->cpuid.edx &= mask->cpuid.edx;
255 256
}

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

static virCPUx86FeaturePtr
x86FeatureFind(virCPUx86MapPtr map,
               const char *name)
{
    size_t i;

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

    return NULL;
}


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


288
static int
289
virCPUx86DataSorter(const void *a, const void *b)
290
{
291 292
    virCPUx86DataItemPtr da = (virCPUx86DataItemPtr) a;
    virCPUx86DataItemPtr db = (virCPUx86DataItemPtr) b;
293

294
    if (da->cpuid.eax_in > db->cpuid.eax_in)
295
        return 1;
296
    else if (da->cpuid.eax_in < db->cpuid.eax_in)
297 298
        return -1;

299
    if (da->cpuid.ecx_in > db->cpuid.ecx_in)
300
        return 1;
301
    else if (da->cpuid.ecx_in < db->cpuid.ecx_in)
302 303
        return -1;

304 305 306
    return 0;
}

307 308 309 310 311 312 313
static int
virCPUx86DataItemCmp(const virCPUx86DataItem *item1,
                     const virCPUx86DataItem *item2)
{
    return virCPUx86DataSorter(item1, item2);
}

314

315
/* skips all zero CPUID leaves */
316
static virCPUx86DataItemPtr
317
virCPUx86DataNext(virCPUx86DataIteratorPtr iterator)
J
Jiri Denemark 已提交
318
{
319
    const virCPUx86Data *data = iterator->data;
320
    virCPUx86DataItem zero = { 0 };
J
Jiri Denemark 已提交
321

322
    if (!data)
J
Jiri Denemark 已提交
323 324
        return NULL;

325
    while (++iterator->pos < data->len) {
326 327
        virCPUx86DataItemPtr item = data->items + iterator->pos;

328
        if (!virCPUx86DataItemMatch(item, &zero))
329
            return item;
330
    }
J
Jiri Denemark 已提交
331

332
    return NULL;
J
Jiri Denemark 已提交
333 334 335
}


336
static virCPUx86DataItemPtr
J
Jiri Denemark 已提交
337 338
virCPUx86DataGet(const virCPUx86Data *data,
                 const virCPUx86DataItem *item)
J
Jiri Denemark 已提交
339
{
340
    size_t i;
J
Jiri Denemark 已提交
341

342
    for (i = 0; i < data->len; i++) {
343 344 345
        virCPUx86DataItemPtr di = data->items + i;
        if (virCPUx86DataItemCmp(di, item) == 0)
            return di;
J
Jiri Denemark 已提交
346 347
    }

348
    return NULL;
J
Jiri Denemark 已提交
349 350
}

351
static void
352
virCPUx86DataClear(virCPUx86Data *data)
J
Jiri Denemark 已提交
353
{
354
    if (!data)
J
Jiri Denemark 已提交
355 356
        return;

357
    VIR_FREE(data->items);
J
Jiri Denemark 已提交
358 359 360
}


361
static void
J
Jiri Denemark 已提交
362
virCPUx86DataFree(virCPUDataPtr data)
363 364 365 366
{
    if (!data)
        return;

367
    virCPUx86DataClear(&data->data.x86);
368 369 370 371
    VIR_FREE(data);
}


372 373
static int
x86DataCopy(virCPUx86Data *dst, const virCPUx86Data *src)
J
Jiri Denemark 已提交
374
{
375
    size_t i;
J
Jiri Denemark 已提交
376

377
    if (VIR_ALLOC_N(dst->items, src->len) < 0)
378
        return -1;
J
Jiri Denemark 已提交
379

380 381
    dst->len = src->len;
    for (i = 0; i < src->len; i++)
382
        dst->items[i] = src->items[i];
J
Jiri Denemark 已提交
383

384
    return 0;
J
Jiri Denemark 已提交
385 386 387
}


388
static int
389 390
virCPUx86DataAddItem(virCPUx86Data *data,
                     const virCPUx86DataItem *item)
J
Jiri Denemark 已提交
391
{
392
    virCPUx86DataItemPtr existing;
J
Jiri Denemark 已提交
393

J
Jiri Denemark 已提交
394
    if ((existing = virCPUx86DataGet(data, item))) {
395
        virCPUx86DataItemSetBits(existing, item);
396
    } else {
397
        if (VIR_APPEND_ELEMENT_COPY(data->items, data->len,
398
                                    *((virCPUx86DataItemPtr)item)) < 0)
399
            return -1;
J
Jiri Denemark 已提交
400

401
        qsort(data->items, data->len,
402
              sizeof(virCPUx86DataItem), virCPUx86DataSorter);
403
    }
J
Jiri Denemark 已提交
404

J
Jiri Denemark 已提交
405 406 407 408 409
    return 0;
}


static int
410 411
x86DataAdd(virCPUx86Data *data1,
           const virCPUx86Data *data2)
J
Jiri Denemark 已提交
412
{
413
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data2);
J
Jiri Denemark 已提交
414 415 416 417 418
    virCPUx86DataItemPtr item;

    while ((item = virCPUx86DataNext(&iter))) {
        if (virCPUx86DataAddItem(data1, item) < 0)
            return -1;
J
Jiri Denemark 已提交
419
    }
J
Jiri Denemark 已提交
420 421 422 423 424

    return 0;
}


425
static void
426 427
x86DataSubtract(virCPUx86Data *data1,
                const virCPUx86Data *data2)
428
{
429
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data1);
430 431
    virCPUx86DataItemPtr item1;
    virCPUx86DataItemPtr item2;
432

433
    while ((item1 = virCPUx86DataNext(&iter))) {
434 435
        item2 = virCPUx86DataGet(data2, item1);
        virCPUx86DataItemClearBits(item1, item2);
436 437 438 439
    }
}


J
Jiri Denemark 已提交
440
static void
441 442
x86DataIntersect(virCPUx86Data *data1,
                 const virCPUx86Data *data2)
443
{
444
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data1);
445 446
    virCPUx86DataItemPtr item1;
    virCPUx86DataItemPtr item2;
447

448
    while ((item1 = virCPUx86DataNext(&iter))) {
J
Jiri Denemark 已提交
449
        item2 = virCPUx86DataGet(data2, item1);
450
        if (item2)
451
            virCPUx86DataItemAndBits(item1, item2);
J
Jiri Denemark 已提交
452
        else
453
            virCPUx86DataItemClearBits(item1, item1);
454 455 456 457
    }
}


J
Jiri Denemark 已提交
458
static bool
459
x86DataIsEmpty(virCPUx86Data *data)
J
Jiri Denemark 已提交
460
{
461
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(data);
J
Jiri Denemark 已提交
462

463
    return !virCPUx86DataNext(&iter);
J
Jiri Denemark 已提交
464
}
J
Jiri Denemark 已提交
465 466


J
Jiri Denemark 已提交
467
static bool
468 469
x86DataIsSubset(const virCPUx86Data *data,
                const virCPUx86Data *subset)
J
Jiri Denemark 已提交
470
{
471
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit((virCPUx86Data *)subset);
472 473
    const virCPUx86DataItem *item;
    const virCPUx86DataItem *itemSubset;
J
Jiri Denemark 已提交
474

475
    while ((itemSubset = virCPUx86DataNext(&iter))) {
J
Jiri Denemark 已提交
476
        if (!(item = virCPUx86DataGet(data, itemSubset)) ||
477
            !virCPUx86DataItemMatchMasked(item, itemSubset))
J
Jiri Denemark 已提交
478
            return false;
J
Jiri Denemark 已提交
479 480
    }

J
Jiri Denemark 已提交
481
    return true;
J
Jiri Denemark 已提交
482 483 484
}


485 486 487 488
/* also removes all detected features from data */
static int
x86DataToCPUFeatures(virCPUDefPtr cpu,
                     int policy,
489
                     virCPUx86Data *data,
J
Jiri Denemark 已提交
490
                     virCPUx86MapPtr map)
491
{
492
    size_t i;
493

494 495
    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];
496 497
        if (x86DataIsSubset(data, &feature->data)) {
            x86DataSubtract(data, &feature->data);
J
Jiri Denemark 已提交
498 499
            if (virCPUDefAddFeature(cpu, feature->name, policy) < 0)
                return -1;
500 501 502 503 504 505 506
        }
    }

    return 0;
}


J
Jiri Denemark 已提交
507
/* also removes bits corresponding to vendor string from data */
508
static virCPUx86VendorPtr
J
Jiri Denemark 已提交
509
x86DataToVendor(const virCPUx86Data *data,
J
Jiri Denemark 已提交
510
                virCPUx86MapPtr map)
J
Jiri Denemark 已提交
511
{
512
    virCPUx86DataItemPtr item;
513
    size_t i;
J
Jiri Denemark 已提交
514

515 516
    for (i = 0; i < map->nvendors; i++) {
        virCPUx86VendorPtr vendor = map->vendors[i];
J
Jiri Denemark 已提交
517
        if ((item = virCPUx86DataGet(data, &vendor->data)) &&
518
            virCPUx86DataItemMatchMasked(item, &vendor->data)) {
519
            virCPUx86DataItemClearBits(item, &vendor->data);
J
Jiri Denemark 已提交
520 521 522 523 524 525 526 527
            return vendor;
        }
    }

    return NULL;
}


528
static int
529 530
virCPUx86VendorToData(const char *vendor,
                      virCPUx86DataItemPtr data)
531
{
532 533
    virCPUx86CPUIDPtr cpuid = &data->cpuid;

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    if (strlen(vendor) != VENDOR_STRING_LENGTH) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid CPU vendor string '%s'"), vendor);
        return -1;
    }

    cpuid->eax_in = 0;
    cpuid->ecx_in = 0;
    cpuid->ebx = virReadBufInt32LE(vendor);
    cpuid->edx = virReadBufInt32LE(vendor + 4);
    cpuid->ecx = virReadBufInt32LE(vendor + 8);

    return 0;
}


550 551
static uint32_t
x86MakeSignature(unsigned int family,
552 553
                 unsigned int model,
                 unsigned int stepping)
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
{
    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]
573
     * stepping = eax[3:0]
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
     */

    /* 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;

593 594
    /* Step */
    sig |= stepping & 0xf;
595 596 597 598 599

    return sig;
}


600 601 602 603 604 605
static void
x86DataToSignatureFull(const virCPUx86Data *data,
                       unsigned int *family,
                       unsigned int *model,
                       unsigned int *stepping)
{
606 607 608
    virCPUx86DataItem leaf1 = CPUID(.eax_in = 0x1);
    virCPUx86DataItemPtr item;
    virCPUx86CPUIDPtr cpuid;
609 610 611

    *family = *model = *stepping = 0;

J
Jiri Denemark 已提交
612
    if (!(item = virCPUx86DataGet(data, &leaf1)))
613 614
        return;

615
    cpuid = &item->cpuid;
616 617 618 619 620 621
    *family = ((cpuid->eax >> 20) & 0xff) + ((cpuid->eax >> 8) & 0xf);
    *model = ((cpuid->eax >> 12) & 0xf0) + ((cpuid->eax >> 4) & 0xf);
    *stepping = cpuid->eax & 0xf;
}


622 623 624 625 626 627
/* Mask out irrelevant bits (R and Step) from processor signature. */
#define SIGNATURE_MASK  0x0fff3ff0

static uint32_t
x86DataToSignature(const virCPUx86Data *data)
{
628
    virCPUx86DataItem leaf1 = CPUID(.eax_in = 0x1);
629
    virCPUx86DataItemPtr item;
630

J
Jiri Denemark 已提交
631
    if (!(item = virCPUx86DataGet(data, &leaf1)))
632 633
        return 0;

634
    return item->cpuid.eax & SIGNATURE_MASK;
635 636 637 638 639 640 641
}


static int
x86DataAddSignature(virCPUx86Data *data,
                    uint32_t signature)
{
642
    virCPUx86DataItem leaf1 = CPUID(.eax_in = 0x1, .eax = signature);
643

644
    return virCPUx86DataAddItem(data, &leaf1);
645 646 647
}


648
static virCPUDefPtr
649
x86DataToCPU(const virCPUx86Data *data,
J
Jiri Denemark 已提交
650
             virCPUx86ModelPtr model,
651 652
             virCPUx86MapPtr map,
             virDomainCapsCPUModelPtr hvModel)
653 654
{
    virCPUDefPtr cpu;
655 656
    virCPUx86Data copy = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data modelData = VIR_CPU_X86_DATA_INIT;
657
    virCPUx86VendorPtr vendor;
658 659

    if (VIR_ALLOC(cpu) < 0 ||
660
        VIR_STRDUP(cpu->model, model->name) < 0 ||
661 662
        x86DataCopy(&copy, data) < 0 ||
        x86DataCopy(&modelData, &model->data) < 0)
663
        goto error;
664

665
    if ((vendor = x86DataToVendor(&copy, map)) &&
666
        VIR_STRDUP(cpu->vendor, vendor->name) < 0)
667
        goto error;
J
Jiri Denemark 已提交
668

669 670
    x86DataSubtract(&copy, &modelData);
    x86DataSubtract(&modelData, data);
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    /* The hypervisor's version of the CPU model (hvModel) may contain
     * additional features which may be currently unavailable. Such features
     * block usage of the CPU model and we need to explicitly disable them.
     */
    if (hvModel && hvModel->blockers) {
        char **blocker;
        virCPUx86FeaturePtr feature;

        for (blocker = hvModel->blockers; *blocker; blocker++) {
            if ((feature = x86FeatureFind(map, *blocker)) &&
                !x86DataIsSubset(&copy, &feature->data))
                x86DataAdd(&modelData, &feature->data);
        }
    }

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

690 691
    if (x86DataToCPUFeatures(cpu, VIR_CPU_FEATURE_REQUIRE, &copy, map) ||
        x86DataToCPUFeatures(cpu, VIR_CPU_FEATURE_DISABLE, &modelData, map))
692
        goto error;
693

694
 cleanup:
695 696
    virCPUx86DataClear(&modelData);
    virCPUx86DataClear(&copy);
697 698
    return cpu;

699
 error:
700 701 702 703 704 705
    virCPUDefFree(cpu);
    cpu = NULL;
    goto cleanup;
}


J
Jiri Denemark 已提交
706
static void
707
x86VendorFree(virCPUx86VendorPtr vendor)
J
Jiri Denemark 已提交
708 709 710 711 712 713
{
    if (!vendor)
        return;

    VIR_FREE(vendor->name);
    VIR_FREE(vendor);
J
Jiri Denemark 已提交
714
}
J
Jiri Denemark 已提交
715 716


717
static virCPUx86VendorPtr
J
Jiri Denemark 已提交
718
x86VendorFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
719 720
              const char *name)
{
721
    size_t i;
J
Jiri Denemark 已提交
722

723 724 725
    for (i = 0; i < map->nvendors; i++) {
        if (STREQ(map->vendors[i]->name, name))
            return map->vendors[i];
J
Jiri Denemark 已提交
726 727 728 729 730 731
    }

    return NULL;
}


732
static int
J
Jiri Denemark 已提交
733
x86VendorParse(xmlXPathContextPtr ctxt,
734 735
               const char *name,
               void *data)
J
Jiri Denemark 已提交
736
{
737
    virCPUx86MapPtr map = data;
738
    virCPUx86VendorPtr vendor = NULL;
J
Jiri Denemark 已提交
739
    char *string = NULL;
740
    int ret = -1;
J
Jiri Denemark 已提交
741 742

    if (VIR_ALLOC(vendor) < 0)
743
        goto cleanup;
J
Jiri Denemark 已提交
744

745
    if (VIR_STRDUP(vendor->name, name) < 0)
746
        goto cleanup;
J
Jiri Denemark 已提交
747 748

    if (x86VendorFind(map, vendor->name)) {
749 750
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU vendor %s already defined"), vendor->name);
751
        goto cleanup;
J
Jiri Denemark 已提交
752 753 754 755
    }

    string = virXPathString("string(@string)", ctxt);
    if (!string) {
756
        virReportError(VIR_ERR_INTERNAL_ERROR,
757 758
                       _("Missing vendor string for CPU vendor %s"),
                       vendor->name);
759
        goto cleanup;
J
Jiri Denemark 已提交
760 761
    }

762
    if (virCPUx86VendorToData(string, &vendor->data) < 0)
763
        goto cleanup;
E
Eric Blake 已提交
764

765
    if (VIR_APPEND_ELEMENT(map->vendors, map->nvendors, vendor) < 0)
766
        goto cleanup;
767 768 769

    ret = 0;

J
Jiri Denemark 已提交
770
 cleanup:
771
    x86VendorFree(vendor);
J
Jiri Denemark 已提交
772
    VIR_FREE(string);
773
    return ret;
J
Jiri Denemark 已提交
774 775 776
}


777
static virCPUx86FeaturePtr
J
Jiri Denemark 已提交
778 779
x86FeatureNew(void)
{
780
    virCPUx86FeaturePtr feature;
J
Jiri Denemark 已提交
781 782 783 784 785 786 787 788

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

    return feature;
}


J
Jiri Denemark 已提交
789
static void
790
x86FeatureFree(virCPUx86FeaturePtr feature)
J
Jiri Denemark 已提交
791
{
792
    if (!feature)
J
Jiri Denemark 已提交
793 794 795
        return;

    VIR_FREE(feature->name);
796
    virCPUx86DataClear(&feature->data);
J
Jiri Denemark 已提交
797 798 799 800
    VIR_FREE(feature);
}


J
Jiri Denemark 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
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;
}


822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
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;
}


838
static char *
J
Jiri Denemark 已提交
839
x86FeatureNames(virCPUx86MapPtr map,
840
                const char *separator,
841
                virCPUx86Data *data)
842 843 844
{
    virBuffer ret = VIR_BUFFER_INITIALIZER;
    bool first = true;
845
    size_t i;
846 847 848

    virBufferAdd(&ret, "", 0);

849 850
    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];
851
        if (x86DataIsSubset(data, &feature->data)) {
852 853 854 855 856
            if (!first)
                virBufferAdd(&ret, separator, -1);
            else
                first = false;

857
            virBufferAdd(&ret, feature->name, -1);
858 859 860 861 862 863 864
        }
    }

    return virBufferContentAndReset(&ret);
}


865 866
static int
x86ParseCPUID(xmlXPathContextPtr ctxt,
867
              virCPUx86DataItemPtr item)
868
{
869
    virCPUx86CPUIDPtr cpuid;
870
    unsigned long eax_in, ecx_in;
871
    unsigned long eax, ebx, ecx, edx;
872
    int ret_eax_in, ret_ecx_in, ret_eax, ret_ebx, ret_ecx, ret_edx;
873

874
    memset(item, 0, sizeof(*item));
875

876
    eax_in = ecx_in = 0;
877 878
    eax = ebx = ecx = edx = 0;
    ret_eax_in = virXPathULongHex("string(@eax_in)", ctxt, &eax_in);
879
    ret_ecx_in = virXPathULongHex("string(@ecx_in)", ctxt, &ecx_in);
880 881 882 883 884
    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);

885
    if (ret_eax_in < 0 || ret_ecx_in == -2 ||
886
        ret_eax == -2 || ret_ebx == -2 || ret_ecx == -2 || ret_edx == -2)
887 888
        return -1;

889
    cpuid = &item->cpuid;
890
    cpuid->eax_in = eax_in;
891
    cpuid->ecx_in = ecx_in;
892 893 894 895 896 897 898 899
    cpuid->eax = eax;
    cpuid->ebx = ebx;
    cpuid->ecx = ecx;
    cpuid->edx = edx;
    return 0;
}


900
static int
J
Jiri Denemark 已提交
901
x86FeatureParse(xmlXPathContextPtr ctxt,
902 903
                const char *name,
                void *data)
J
Jiri Denemark 已提交
904
{
905
    virCPUx86MapPtr map = data;
J
Jiri Denemark 已提交
906
    xmlNodePtr *nodes = NULL;
907
    virCPUx86FeaturePtr feature;
908
    virCPUx86DataItem item;
909
    size_t i;
J
Jiri Denemark 已提交
910
    int n;
911
    char *str = NULL;
912
    int ret = -1;
J
Jiri Denemark 已提交
913

J
Jiri Denemark 已提交
914
    if (!(feature = x86FeatureNew()))
915
        goto cleanup;
J
Jiri Denemark 已提交
916

J
Jiri Denemark 已提交
917
    feature->migratable = true;
918 919

    if (VIR_STRDUP(feature->name, name) < 0)
920
        goto cleanup;
J
Jiri Denemark 已提交
921 922

    if (x86FeatureFind(map, feature->name)) {
923 924
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU feature %s already defined"), feature->name);
925
        goto cleanup;
J
Jiri Denemark 已提交
926 927
    }

928 929
    str = virXPathString("string(@migratable)", ctxt);
    if (STREQ_NULLABLE(str, "no"))
J
Jiri Denemark 已提交
930
        feature->migratable = false;
931

932
    n = virXPathNodeSet("./cpuid", ctxt, &nodes);
J
Jiri Denemark 已提交
933
    if (n < 0)
934
        goto cleanup;
J
Jiri Denemark 已提交
935

936 937 938 939 940 941 942
    if (n == 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing cpuid for feature %s"),
                       feature->name);
        goto cleanup;
    }

J
Jiri Denemark 已提交
943 944
    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
945
        if (x86ParseCPUID(ctxt, &item) < 0) {
946
            virReportError(VIR_ERR_INTERNAL_ERROR,
947 948
                           _("Invalid cpuid[%zu] in %s feature"),
                           i, feature->name);
949
            goto cleanup;
J
Jiri Denemark 已提交
950
        }
951
        if (virCPUx86DataAddItem(&feature->data, &item))
952
            goto cleanup;
J
Jiri Denemark 已提交
953 954
    }

955 956 957 958
    if (!feature->migratable &&
        VIR_APPEND_ELEMENT_COPY(map->migrate_blockers,
                                map->nblockers,
                                feature) < 0)
959
        goto cleanup;
960 961

    if (VIR_APPEND_ELEMENT(map->features, map->nfeatures, feature) < 0)
962
        goto cleanup;
963 964 965

    ret = 0;

J
Jiri Denemark 已提交
966
 cleanup:
967
    x86FeatureFree(feature);
968
    VIR_FREE(nodes);
969
    VIR_FREE(str);
970
    return ret;
J
Jiri Denemark 已提交
971 972 973
}


J
Jiri Denemark 已提交
974
static virCPUx86ModelPtr
J
Jiri Denemark 已提交
975 976
x86ModelNew(void)
{
J
Jiri Denemark 已提交
977
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
978 979 980 981 982 983 984 985

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

    return model;
}


J
Jiri Denemark 已提交
986
static void
J
Jiri Denemark 已提交
987
x86ModelFree(virCPUx86ModelPtr model)
J
Jiri Denemark 已提交
988
{
989
    if (!model)
J
Jiri Denemark 已提交
990 991 992
        return;

    VIR_FREE(model->name);
993
    VIR_FREE(model->signatures);
994
    virCPUx86DataClear(&model->data);
J
Jiri Denemark 已提交
995 996 997 998
    VIR_FREE(model);
}


999 1000 1001 1002
static int
x86ModelCopySignatures(virCPUx86ModelPtr dst,
                       virCPUx86ModelPtr src)
{
1003 1004
    size_t i;

1005 1006 1007
    if (src->nsignatures == 0)
        return 0;

1008 1009 1010 1011 1012 1013
    if (VIR_ALLOC_N(dst->signatures, src->nsignatures) < 0)
        return -1;

    dst->nsignatures = src->nsignatures;
    for (i = 0; i < src->nsignatures; i++)
        dst->signatures[i] = src->signatures[i];
1014 1015 1016 1017 1018

    return 0;
}


J
Jiri Denemark 已提交
1019 1020
static virCPUx86ModelPtr
x86ModelCopy(virCPUx86ModelPtr model)
J
Jiri Denemark 已提交
1021
{
J
Jiri Denemark 已提交
1022
    virCPUx86ModelPtr copy;
J
Jiri Denemark 已提交
1023

1024 1025
    if (VIR_ALLOC(copy) < 0 ||
        VIR_STRDUP(copy->name, model->name) < 0 ||
1026
        x86ModelCopySignatures(copy, model) < 0 ||
1027
        x86DataCopy(&copy->data, &model->data) < 0) {
J
Jiri Denemark 已提交
1028 1029 1030 1031
        x86ModelFree(copy);
        return NULL;
    }

J
Jiri Denemark 已提交
1032
    copy->vendor = model->vendor;
J
Jiri Denemark 已提交
1033 1034 1035 1036 1037

    return copy;
}


J
Jiri Denemark 已提交
1038
static virCPUx86ModelPtr
J
Jiri Denemark 已提交
1039
x86ModelFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
1040 1041
             const char *name)
{
1042
    size_t i;
J
Jiri Denemark 已提交
1043

1044 1045 1046
    for (i = 0; i < map->nmodels; i++) {
        if (STREQ(map->models[i]->name, name))
            return map->models[i];
J
Jiri Denemark 已提交
1047 1048 1049 1050 1051 1052
    }

    return NULL;
}


1053 1054 1055 1056 1057 1058 1059 1060 1061
/*
 * 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 已提交
1062
static virCPUx86ModelPtr
1063
x86ModelFromCPU(const virCPUDef *cpu,
J
Jiri Denemark 已提交
1064
                virCPUx86MapPtr map,
J
Jiri Denemark 已提交
1065 1066
                int policy)
{
J
Jiri Denemark 已提交
1067
    virCPUx86ModelPtr model = NULL;
1068
    size_t i;
J
Jiri Denemark 已提交
1069

1070 1071 1072 1073
    /* host CPU only contains required features; requesting other features
     * just returns an empty model
     */
    if (cpu->type == VIR_CPU_TYPE_HOST &&
1074 1075
        policy != VIR_CPU_FEATURE_REQUIRE &&
        policy != -1)
1076 1077
        return x86ModelNew();

J
Jiri Denemark 已提交
1078 1079
    if (cpu->model &&
        (policy == VIR_CPU_FEATURE_REQUIRE || policy == -1)) {
1080
        if (!(model = x86ModelFind(map, cpu->model))) {
1081 1082
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU model %s"), cpu->model);
1083
            return NULL;
J
Jiri Denemark 已提交
1084 1085
        }

1086 1087 1088
        model = x86ModelCopy(model);
    } else {
        model = x86ModelNew();
J
Jiri Denemark 已提交
1089
    }
J
Jiri Denemark 已提交
1090

1091 1092 1093
    if (!model)
        return NULL;

J
Jiri Denemark 已提交
1094
    for (i = 0; i < cpu->nfeatures; i++) {
1095
        virCPUx86FeaturePtr feature;
1096
        virCPUFeaturePolicy fpol;
J
Jiri Denemark 已提交
1097

1098 1099 1100 1101 1102 1103 1104
        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 已提交
1105 1106
            continue;

1107
        if (!(feature = x86FeatureFind(map, cpu->features[i].name))) {
1108 1109
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU feature %s"), cpu->features[i].name);
J
Jiri Denemark 已提交
1110 1111 1112
            goto error;
        }

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
        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) {
1132
            goto error;
1133
        }
J
Jiri Denemark 已提交
1134 1135 1136 1137
    }

    return model;

1138
 error:
J
Jiri Denemark 已提交
1139 1140 1141 1142 1143
    x86ModelFree(model);
    return NULL;
}


1144
static virCPUx86CompareResult
J
Jiri Denemark 已提交
1145 1146
x86ModelCompare(virCPUx86ModelPtr model1,
                virCPUx86ModelPtr model2)
J
Jiri Denemark 已提交
1147
{
1148
    virCPUx86CompareResult result = EQUAL;
1149 1150
    virCPUx86DataIterator iter1 = virCPUx86DataIteratorInit(&model1->data);
    virCPUx86DataIterator iter2 = virCPUx86DataIteratorInit(&model2->data);
1151 1152
    virCPUx86DataItemPtr item1;
    virCPUx86DataItemPtr item2;
J
Jiri Denemark 已提交
1153

1154
    while ((item1 = virCPUx86DataNext(&iter1))) {
1155
        virCPUx86CompareResult match = SUPERSET;
J
Jiri Denemark 已提交
1156

J
Jiri Denemark 已提交
1157
        if ((item2 = virCPUx86DataGet(&model2->data, item1))) {
1158
            if (virCPUx86DataItemMatch(item1, item2))
J
Jiri Denemark 已提交
1159
                continue;
1160
            else if (!virCPUx86DataItemMatchMasked(item1, item2))
J
Jiri Denemark 已提交
1161 1162 1163 1164 1165 1166 1167 1168 1169
                match = SUBSET;
        }

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

1170
    while ((item2 = virCPUx86DataNext(&iter2))) {
1171
        virCPUx86CompareResult match = SUBSET;
J
Jiri Denemark 已提交
1172

J
Jiri Denemark 已提交
1173
        if ((item1 = virCPUx86DataGet(&model1->data, item2))) {
1174
            if (virCPUx86DataItemMatch(item2, item1))
J
Jiri Denemark 已提交
1175
                continue;
1176
            else if (!virCPUx86DataItemMatchMasked(item2, item1))
J
Jiri Denemark 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
                match = SUPERSET;
        }

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

    return result;
}


1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
static int
x86ModelParseAncestor(virCPUx86ModelPtr model,
                      xmlXPathContextPtr ctxt,
                      virCPUx86MapPtr map)
{
    VIR_AUTOFREE(char *) name = NULL;
    virCPUx86ModelPtr ancestor;
    int rc;

    if ((rc = virXPathBoolean("boolean(./model)", ctxt)) <= 0)
        return rc;

    name = virXPathString("string(./model/@name)", ctxt);
    if (!name) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing ancestor's name in CPU model %s"),
                       model->name);
        return -1;
    }

    if (!(ancestor = x86ModelFind(map, name))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Ancestor model %s not found for CPU model %s"),
                       name, model->name);
        return -1;
    }

    model->vendor = ancestor->vendor;
1218 1219
    if (x86ModelCopySignatures(model, ancestor) < 0 ||
        x86DataCopy(&model->data, &ancestor->data) < 0)
1220 1221 1222 1223 1224 1225
        return -1;

    return 0;
}


1226
static int
1227 1228
x86ModelParseSignatures(virCPUx86ModelPtr model,
                        xmlXPathContextPtr ctxt)
J
Jiri Denemark 已提交
1229
{
1230 1231 1232 1233 1234 1235 1236 1237
    VIR_AUTOFREE(xmlNodePtr *) nodes = NULL;
    xmlNodePtr root = ctxt->node;
    size_t i;
    int n;

    if ((n = virXPathNodeSet("./signature", ctxt, &nodes)) <= 0)
        return n;

1238 1239
    /* Remove inherited signatures. */
    VIR_FREE(model->signatures);
J
Jiri Denemark 已提交
1240

1241 1242 1243 1244 1245
    model->nsignatures = n;
    if (VIR_ALLOC_N(model->signatures, n) < 0)
       return -1;

    for (i = 0; i < n; i++) {
1246 1247 1248 1249
        unsigned int sigFamily = 0;
        unsigned int sigModel = 0;
        int rc;

1250
        ctxt->node = nodes[i];
1251

1252
        rc = virXPathUInt("string(@family)", ctxt, &sigFamily);
1253 1254 1255 1256
        if (rc < 0 || sigFamily == 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid CPU signature family in model %s"),
                           model->name);
1257
            return -1;
1258 1259
        }

1260
        rc = virXPathUInt("string(@model)", ctxt, &sigModel);
1261 1262 1263 1264
        if (rc < 0 || sigModel == 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid CPU signature model in model %s"),
                           model->name);
1265
            return -1;
1266 1267
        }

1268
        model->signatures[i] = x86MakeSignature(sigFamily, sigModel, 0);
1269 1270
    }

1271
    ctxt->node = root;
1272 1273 1274 1275
    return 0;
}


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 1303 1304 1305
static int
x86ModelParseVendor(virCPUx86ModelPtr model,
                    xmlXPathContextPtr ctxt,
                    virCPUx86MapPtr map)
{
    VIR_AUTOFREE(char *) vendor = NULL;
    int rc;

    if ((rc = virXPathBoolean("boolean(./vendor)", ctxt)) <= 0)
        return rc;

    vendor = virXPathString("string(./vendor/@name)", ctxt);
    if (!vendor) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid vendor element in CPU model %s"),
                       model->name);
        return -1;
    }

    if (!(model->vendor = x86VendorFind(map, vendor))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown vendor %s referenced by CPU model %s"),
                       vendor, model->name);
        return -1;
    }

    return 0;
}


1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
static int
x86ModelParseFeatures(virCPUx86ModelPtr model,
                      xmlXPathContextPtr ctxt,
                      virCPUx86MapPtr map)
{
    VIR_AUTOFREE(xmlNodePtr *) nodes = NULL;
    size_t i;
    int n;

    if ((n = virXPathNodeSet("./feature", ctxt, &nodes)) <= 0)
        return n;

    for (i = 0; i < n; i++) {
        VIR_AUTOFREE(char *) ftname = NULL;
        virCPUx86FeaturePtr feature;

        if (!(ftname = virXMLPropString(nodes[i], "name"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Missing feature name for CPU model %s"),
                           model->name);
            return -1;
        }

        if (!(feature = x86FeatureFind(map, ftname))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Feature %s required by CPU model %s not found"),
                           ftname, model->name);
            return -1;
        }

        if (x86DataAdd(&model->data, &feature->data))
            return -1;
    }

    return 0;
}


1344 1345 1346 1347 1348 1349
static int
x86ModelParse(xmlXPathContextPtr ctxt,
              const char *name,
              void *data)
{
    virCPUx86MapPtr map = data;
1350
    virCPUx86ModelPtr model = NULL;
1351 1352
    int ret = -1;

1353 1354 1355 1356 1357 1358
    if (x86ModelFind(map, name)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Multiple definitions of CPU model '%s'"), name);
        goto cleanup;
    }

1359 1360 1361 1362 1363 1364 1365 1366 1367
    if (!(model = x86ModelNew()))
        goto cleanup;

    if (VIR_STRDUP(model->name, name) < 0)
        goto cleanup;

    if (x86ModelParseAncestor(model, ctxt, map) < 0)
        goto cleanup;

1368
    if (x86ModelParseSignatures(model, ctxt) < 0)
1369 1370
        goto cleanup;

1371 1372
    if (x86ModelParseVendor(model, ctxt, map) < 0)
        goto cleanup;
J
Jiri Denemark 已提交
1373

1374
    if (x86ModelParseFeatures(model, ctxt, map) < 0)
1375
        goto cleanup;
J
Jiri Denemark 已提交
1376

1377
    if (VIR_APPEND_ELEMENT(map->models, map->nmodels, model) < 0)
1378
        goto cleanup;
1379 1380 1381

    ret = 0;

J
Jiri Denemark 已提交
1382
 cleanup:
1383
    x86ModelFree(model);
1384
    return ret;
J
Jiri Denemark 已提交
1385 1386 1387
}


J
Jiri Denemark 已提交
1388
static void
J
Jiri Denemark 已提交
1389
x86MapFree(virCPUx86MapPtr map)
J
Jiri Denemark 已提交
1390
{
1391 1392
    size_t i;

1393
    if (!map)
J
Jiri Denemark 已提交
1394 1395
        return;

1396 1397 1398
    for (i = 0; i < map->nfeatures; i++)
        x86FeatureFree(map->features[i]);
    VIR_FREE(map->features);
J
Jiri Denemark 已提交
1399

1400 1401 1402
    for (i = 0; i < map->nmodels; i++)
        x86ModelFree(map->models[i]);
    VIR_FREE(map->models);
J
Jiri Denemark 已提交
1403

1404 1405 1406
    for (i = 0; i < map->nvendors; i++)
        x86VendorFree(map->vendors[i]);
    VIR_FREE(map->vendors);
1407

1408 1409 1410 1411
    /* migrate_blockers only points to the features from map->features list,
     * which were already freed above
     */
    VIR_FREE(map->migrate_blockers);
1412

J
Jiri Denemark 已提交
1413 1414 1415 1416
    VIR_FREE(map);
}


J
Jiri Denemark 已提交
1417
static virCPUx86MapPtr
1418
virCPUx86LoadMap(void)
J
Jiri Denemark 已提交
1419
{
J
Jiri Denemark 已提交
1420
    virCPUx86MapPtr map;
J
Jiri Denemark 已提交
1421

1422
    if (VIR_ALLOC(map) < 0)
J
Jiri Denemark 已提交
1423 1424
        return NULL;

1425
    if (cpuMapLoad("x86", x86VendorParse, x86FeatureParse, x86ModelParse, map) < 0)
J
Jiri Denemark 已提交
1426 1427 1428 1429
        goto error;

    return map;

1430
 error:
J
Jiri Denemark 已提交
1431 1432 1433 1434 1435
    x86MapFree(map);
    return NULL;
}


1436
int
1437
virCPUx86DriverOnceInit(void)
1438
{
J
Jiri Denemark 已提交
1439
    if (!(cpuMap = virCPUx86LoadMap()))
1440 1441 1442 1443 1444 1445
        return -1;

    return 0;
}


J
Jiri Denemark 已提交
1446
static virCPUx86MapPtr
1447 1448
virCPUx86GetMap(void)
{
1449
    if (virCPUx86DriverInitialize() < 0)
1450 1451
        return NULL;

J
Jiri Denemark 已提交
1452
    return cpuMap;
1453 1454 1455
}


1456
static char *
J
Jiri Denemark 已提交
1457
virCPUx86DataFormat(const virCPUData *data)
1458
{
1459
    virCPUx86DataIterator iter = virCPUx86DataIteratorInit(&data->data.x86);
1460
    virCPUx86DataItemPtr item;
1461 1462 1463
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "<cpudata arch='x86'>\n");
1464
    while ((item = virCPUx86DataNext(&iter))) {
1465
        virCPUx86CPUIDPtr cpuid = &item->cpuid;
1466
        virBufferAsprintf(&buf,
1467
                          "  <cpuid eax_in='0x%08x' ecx_in='0x%08x'"
1468 1469
                          " eax='0x%08x' ebx='0x%08x'"
                          " ecx='0x%08x' edx='0x%08x'/>\n",
1470
                          cpuid->eax_in, cpuid->ecx_in,
1471 1472 1473 1474
                          cpuid->eax, cpuid->ebx, cpuid->ecx, cpuid->edx);
    }
    virBufferAddLit(&buf, "</cpudata>\n");

1475
    if (virBufferCheckError(&buf) < 0)
1476 1477 1478 1479 1480 1481 1482
        return NULL;

    return virBufferContentAndReset(&buf);
}


static virCPUDataPtr
J
Jiri Denemark 已提交
1483
virCPUx86DataParse(xmlXPathContextPtr ctxt)
1484 1485 1486
{
    xmlNodePtr *nodes = NULL;
    virCPUDataPtr cpuData = NULL;
1487
    virCPUx86DataItem item;
1488 1489 1490
    size_t i;
    int n;

1491
    n = virXPathNodeSet("/cpudata/cpuid", ctxt, &nodes);
J
Jiri Denemark 已提交
1492
    if (n <= 0) {
1493 1494
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no x86 CPU data found"));
1495
        goto error;
1496 1497
    }

1498 1499 1500
    if (!(cpuData = virCPUDataNew(VIR_ARCH_X86_64)))
        goto error;

1501 1502
    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
1503
        if (x86ParseCPUID(ctxt, &item) < 0) {
1504 1505
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to parse cpuid[%zu]"), i);
1506
            goto error;
1507
        }
1508
        if (virCPUx86DataAdd(cpuData, &item) < 0)
1509
            goto error;
1510 1511
    }

1512
 cleanup:
1513 1514
    VIR_FREE(nodes);
    return cpuData;
1515 1516

 error:
J
Jiri Denemark 已提交
1517
    virCPUx86DataFree(cpuData);
1518 1519
    cpuData = NULL;
    goto cleanup;
1520 1521 1522
}


1523 1524 1525
/* A helper macro to exit the cpu computation function without writing
 * redundant code:
 * MSG: error message
1526
 * CPU_DEF: a virCPUx86Data pointer with flags that are conflicting
1527 1528 1529 1530
 * RET: return code to set
 *
 * This macro generates the error string outputs it into logs.
 */
1531 1532 1533 1534 1535 1536 1537 1538
#define virX86CpuIncompatible(MSG, CPU_DEF) \
        do { \
            char *flagsStr = NULL; \
            if (!(flagsStr = x86FeatureNames(map, ", ", (CPU_DEF)))) { \
                virReportOOMError(); \
                goto error; \
            } \
            if (message && \
1539
                virAsprintf(message, "%s: %s", _(MSG), flagsStr) < 0) { \
1540 1541 1542 1543 1544 1545
                VIR_FREE(flagsStr); \
                goto error; \
            } \
            VIR_DEBUG("%s: %s", MSG, flagsStr); \
            VIR_FREE(flagsStr); \
            ret = VIR_CPU_COMPARE_INCOMPATIBLE; \
1546 1547
        } while (0)

1548

J
Jiri Denemark 已提交
1549 1550 1551
static virCPUCompareResult
x86Compute(virCPUDefPtr host,
           virCPUDefPtr cpu,
1552
           virCPUDataPtr *guest,
1553
           char **message)
J
Jiri Denemark 已提交
1554
{
J
Jiri Denemark 已提交
1555
    virCPUx86MapPtr map = NULL;
J
Jiri Denemark 已提交
1556 1557 1558 1559 1560 1561 1562 1563
    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;
1564
    virCPUDataPtr guestData = NULL;
J
Jiri Denemark 已提交
1565
    virCPUCompareResult ret;
1566
    virCPUx86CompareResult result;
J
Jiri Denemark 已提交
1567
    virArch arch;
1568
    size_t i;
J
Jiri Denemark 已提交
1569

1570
    if (cpu->arch != VIR_ARCH_NONE) {
J
Jiri Denemark 已提交
1571 1572 1573
        bool found = false;

        for (i = 0; i < ARRAY_CARDINALITY(archs); i++) {
1574
            if (archs[i] == cpu->arch) {
J
Jiri Denemark 已提交
1575 1576 1577 1578 1579
                found = true;
                break;
            }
        }

1580
        if (!found) {
1581 1582
            VIR_DEBUG("CPU arch %s does not match host arch",
                      virArchToString(cpu->arch));
1583 1584 1585
            if (message &&
                virAsprintf(message,
                            _("CPU arch %s does not match host arch"),
1586
                            virArchToString(cpu->arch)) < 0)
1587
                goto error;
J
Jiri Denemark 已提交
1588
            return VIR_CPU_COMPARE_INCOMPATIBLE;
1589
        }
J
Jiri Denemark 已提交
1590 1591 1592
        arch = cpu->arch;
    } else {
        arch = host->arch;
J
Jiri Denemark 已提交
1593 1594
    }

J
Jiri Denemark 已提交
1595 1596 1597 1598
    if (cpu->vendor &&
        (!host->vendor || STRNEQ(cpu->vendor, host->vendor))) {
        VIR_DEBUG("host CPU vendor does not match required CPU vendor %s",
                  cpu->vendor);
1599 1600 1601 1602 1603
        if (message &&
            virAsprintf(message,
                        _("host CPU vendor does not match required "
                          "CPU vendor %s"),
                        cpu->vendor) < 0)
1604
            goto error;
1605

J
Jiri Denemark 已提交
1606 1607 1608
        return VIR_CPU_COMPARE_INCOMPATIBLE;
    }

1609
    if (!(map = virCPUx86GetMap()) ||
J
Jiri Denemark 已提交
1610
        !(host_model = x86ModelFromCPU(host, map, -1)) ||
J
Jiri Denemark 已提交
1611 1612 1613 1614 1615
        !(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 已提交
1616 1617
        goto error;

1618 1619
    x86DataIntersect(&cpu_forbid->data, &host_model->data);
    if (!x86DataIsEmpty(&cpu_forbid->data)) {
1620
        virX86CpuIncompatible(N_("Host CPU provides forbidden features"),
1621
                              &cpu_forbid->data);
1622
        goto cleanup;
J
Jiri Denemark 已提交
1623 1624
    }

1625 1626 1627
    /* first remove features that were inherited from the CPU model and were
     * explicitly forced, disabled, or made optional
     */
1628 1629 1630
    x86DataSubtract(&cpu_require->data, &cpu_force->data);
    x86DataSubtract(&cpu_require->data, &cpu_optional->data);
    x86DataSubtract(&cpu_require->data, &cpu_disable->data);
J
Jiri Denemark 已提交
1631 1632
    result = x86ModelCompare(host_model, cpu_require);
    if (result == SUBSET || result == UNRELATED) {
1633
        x86DataSubtract(&cpu_require->data, &host_model->data);
1634 1635
        virX86CpuIncompatible(N_("Host CPU does not provide required "
                                 "features"),
1636
                              &cpu_require->data);
1637
        goto cleanup;
J
Jiri Denemark 已提交
1638 1639 1640 1641
    }

    ret = VIR_CPU_COMPARE_IDENTICAL;

1642
    if (!(diff = x86ModelCopy(host_model)))
1643
        goto error;
J
Jiri Denemark 已提交
1644

1645 1646 1647 1648
    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 已提交
1649

1650
    if (!x86DataIsEmpty(&diff->data))
J
Jiri Denemark 已提交
1651
        ret = VIR_CPU_COMPARE_SUPERSET;
J
Jiri Denemark 已提交
1652 1653 1654 1655

    if (ret == VIR_CPU_COMPARE_SUPERSET
        && cpu->type == VIR_CPU_TYPE_GUEST
        && cpu->match == VIR_CPU_MATCH_STRICT) {
1656 1657
        virX86CpuIncompatible(N_("Host CPU does not strictly match guest CPU: "
                                 "Extra features"),
1658
                              &diff->data);
1659
        goto cleanup;
J
Jiri Denemark 已提交
1660 1661
    }

1662 1663
    if (guest) {
        if (!(guest_model = x86ModelCopy(host_model)))
1664
            goto error;
J
Jiri Denemark 已提交
1665

1666
        if (cpu->vendor && host_model->vendor &&
1667 1668
            virCPUx86DataAddItem(&guest_model->data,
                                 &host_model->vendor->data) < 0)
1669 1670
            goto error;

1671 1672
        if (host_model->signatures &&
            x86DataAddSignature(&guest_model->data, *host_model->signatures) < 0)
1673 1674
            goto error;

J
Jiri Denemark 已提交
1675 1676
        if (cpu->type == VIR_CPU_TYPE_GUEST
            && cpu->match == VIR_CPU_MATCH_EXACT)
1677
            x86DataSubtract(&guest_model->data, &diff->data);
J
Jiri Denemark 已提交
1678

1679
        if (x86DataAdd(&guest_model->data, &cpu_force->data))
1680
            goto error;
J
Jiri Denemark 已提交
1681

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

1684 1685
        if (!(guestData = virCPUDataNew(arch)) ||
            x86DataCopy(&guestData->data.x86, &guest_model->data) < 0)
1686
            goto error;
1687 1688

        *guest = guestData;
J
Jiri Denemark 已提交
1689 1690
    }

1691
 cleanup:
J
Jiri Denemark 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    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;

1703
 error:
J
Jiri Denemark 已提交
1704
    virCPUx86DataFree(guestData);
J
Jiri Denemark 已提交
1705
    ret = VIR_CPU_COMPARE_ERROR;
1706
    goto cleanup;
J
Jiri Denemark 已提交
1707
}
1708
#undef virX86CpuIncompatible
J
Jiri Denemark 已提交
1709 1710 1711


static virCPUCompareResult
J
Jiri Denemark 已提交
1712 1713 1714
virCPUx86Compare(virCPUDefPtr host,
                 virCPUDefPtr cpu,
                 bool failIncompatible)
J
Jiri Denemark 已提交
1715
{
J
Jiri Denemark 已提交
1716 1717 1718
    virCPUCompareResult ret = VIR_CPU_COMPARE_ERROR;
    virCPUx86MapPtr map;
    virCPUx86ModelPtr model = NULL;
1719 1720
    char *message = NULL;

J
Jiri Denemark 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
    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;
    }

1732 1733
    ret = x86Compute(host, cpu, NULL, &message);

J
Jiri Denemark 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
    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);
                }
            }
1768 1769 1770
        }
    }

J
Jiri Denemark 已提交
1771 1772 1773
 cleanup:
    VIR_FREE(message);
    x86ModelFree(model);
1774
    return ret;
J
Jiri Denemark 已提交
1775 1776 1777
}


1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
static bool
x86ModelHasSignature(virCPUx86ModelPtr model,
                     uint32_t signature)
{
    size_t i;

    for (i = 0; i < model->nsignatures; i++) {
        if (model->signatures[i] == signature)
            return true;
    }

    return false;
}


1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
static char *
x86FormatSignatures(virCPUx86ModelPtr model)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    size_t i;

    for (i = 0; i < model->nsignatures; i++) {
        virBufferAsprintf(&buf, "%06lx,",
                          (unsigned long)model->signatures[i]);
    }

    virBufferTrim(&buf, ",", -1);

    if (virBufferCheckError(&buf) < 0)
        return NULL;

    return virBufferContentAndReset(&buf);
}


1813
/*
1814 1815
 * Checks whether a candidate model is a better fit for the CPU data than the
 * current model.
1816
 *
1817 1818 1819
 * Returns 0 if current is better,
 *         1 if candidate is better,
 *         2 if candidate is the best one (search should stop now).
1820 1821
 */
static int
1822 1823 1824
x86DecodeUseCandidate(virCPUx86ModelPtr current,
                      virCPUDefPtr cpuCurrent,
                      virCPUx86ModelPtr candidate,
1825
                      virCPUDefPtr cpuCandidate,
1826
                      uint32_t signature,
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
                      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;
        }
    }

1839 1840
    if (preferred && STREQ(cpuCandidate->model, preferred)) {
        VIR_DEBUG("%s is the preferred model", cpuCandidate->model);
1841
        return 2;
1842
    }
1843

1844 1845
    if (!cpuCurrent) {
        VIR_DEBUG("%s is better than nothing", cpuCandidate->model);
1846
        return 1;
1847
    }
1848

1849 1850 1851 1852 1853
    /* 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 &&
1854 1855
        x86ModelHasSignature(current, signature) &&
        !x86ModelHasSignature(candidate, signature)) {
1856 1857
        VIR_DEBUG("%s differs in signature from matching %s",
                  cpuCandidate->model, cpuCurrent->model);
1858
        return 0;
1859
    }
1860

1861 1862 1863
    if (cpuCurrent->nfeatures > cpuCandidate->nfeatures) {
        VIR_DEBUG("%s results in shorter feature list than %s",
                  cpuCandidate->model, cpuCurrent->model);
1864
        return 1;
1865
    }
1866

1867 1868 1869 1870
    /* Prefer a candidate with matching signature even though it would
     * result in longer list of features.
     */
    if (signature &&
1871 1872
        x86ModelHasSignature(candidate, signature) &&
        !x86ModelHasSignature(current, signature)) {
1873
        VIR_DEBUG("%s provides matching signature", cpuCandidate->model);
1874
        return 1;
1875
    }
1876

1877 1878
    VIR_DEBUG("%s does not result in shorter feature list than %s",
              cpuCandidate->model, cpuCurrent->model);
1879 1880 1881 1882
    return 0;
}


1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
/**
 * Drop broken TSX features.
 */
static void
x86DataFilterTSX(virCPUx86Data *data,
                 virCPUx86VendorPtr vendor,
                 virCPUx86MapPtr map)
{
    unsigned int family;
    unsigned int model;
    unsigned int stepping;

    if (!vendor || STRNEQ(vendor->name, "Intel"))
        return;

    x86DataToSignatureFull(data, &family, &model, &stepping);

    if (family == 6 &&
        ((model == 63 && stepping < 4) ||
         model == 60 ||
         model == 69 ||
         model == 70)) {
        virCPUx86FeaturePtr feature;

        VIR_DEBUG("Dropping broken TSX");

        if ((feature = x86FeatureFind(map, "hle")))
            x86DataSubtract(data, &feature->data);

        if ((feature = x86FeatureFind(map, "rtm")))
            x86DataSubtract(data, &feature->data);
    }
}


J
Jiri Denemark 已提交
1918 1919
static int
x86Decode(virCPUDefPtr cpu,
1920
          const virCPUx86Data *cpuData,
1921
          virDomainCapsCPUModelsPtr models,
1922
          const char *preferred,
1923
          bool migratable)
J
Jiri Denemark 已提交
1924 1925
{
    int ret = -1;
J
Jiri Denemark 已提交
1926
    virCPUx86MapPtr map;
J
Jiri Denemark 已提交
1927
    virCPUx86ModelPtr candidate;
1928
    virCPUDefPtr cpuCandidate;
1929
    virCPUx86ModelPtr model = NULL;
1930
    virCPUDefPtr cpuModel = NULL;
1931
    virCPUx86Data data = VIR_CPU_X86_DATA_INIT;
1932 1933
    virCPUx86Data copy = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data features = VIR_CPU_X86_DATA_INIT;
J
Jiri Denemark 已提交
1934
    virCPUx86VendorPtr vendor;
1935
    virDomainCapsCPUModelPtr hvModel = NULL;
1936
    VIR_AUTOFREE(char *) sigs = NULL;
1937
    uint32_t signature;
1938
    ssize_t i;
1939
    int rc;
J
Jiri Denemark 已提交
1940

1941
    if (!cpuData || x86DataCopy(&data, cpuData) < 0)
J
Jiri Denemark 已提交
1942 1943
        return -1;

1944 1945 1946 1947 1948 1949 1950
    if (!(map = virCPUx86GetMap()))
        goto cleanup;

    vendor = x86DataToVendor(&data, map);
    signature = x86DataToSignature(&data);

    x86DataFilterTSX(&data, vendor, map);
J
Jiri Denemark 已提交
1951

1952 1953 1954 1955 1956
    /* 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];
1957 1958
        if (models &&
            !(hvModel = virDomainCapsCPUModelsGet(models, candidate->name))) {
1959 1960
            if (preferred && STREQ(candidate->name, preferred)) {
                if (cpu->fallback != VIR_CPU_FALLBACK_ALLOW) {
1961 1962 1963
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("CPU model %s is not supported by hypervisor"),
                                   preferred);
J
Jiri Denemark 已提交
1964
                    goto cleanup;
1965 1966 1967 1968 1969 1970 1971 1972 1973
                } 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);
            }
1974
            continue;
J
Jiri Denemark 已提交
1975 1976
        }

J
Jiri Denemark 已提交
1977 1978 1979 1980
        /* 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 已提交
1981
            VIR_DEBUG("CPU vendor %s of model %s differs from %s; ignoring",
J
Jiri Denemark 已提交
1982
                      candidate->vendor->name, candidate->name, vendor->name);
1983
            continue;
J
Jiri Denemark 已提交
1984 1985
        }

1986
        if (!(cpuCandidate = x86DataToCPU(&data, candidate, map, hvModel)))
J
Jiri Denemark 已提交
1987 1988 1989
            goto cleanup;
        cpuCandidate->type = cpu->type;

1990 1991 1992
        if ((rc = x86DecodeUseCandidate(model, cpuModel,
                                        candidate, cpuCandidate,
                                        signature, preferred,
1993
                                        cpu->type == VIR_CPU_TYPE_HOST))) {
1994 1995
            virCPUDefFree(cpuModel);
            cpuModel = cpuCandidate;
1996
            model = candidate;
1997 1998
            if (rc == 2)
                break;
1999
        } else {
2000
            virCPUDefFree(cpuCandidate);
2001
        }
J
Jiri Denemark 已提交
2002 2003
    }

2004
    if (!cpuModel) {
2005 2006
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Cannot find suitable CPU model for given data"));
J
Jiri Denemark 已提交
2007
        goto cleanup;
J
Jiri Denemark 已提交
2008 2009
    }

2010 2011 2012
    /* Remove non-migratable features if requested
     * Note: this only works as long as no CPU model contains non-migratable
     * features directly */
2013
    if (migratable) {
2014 2015 2016 2017 2018
        i = 0;
        while (i < cpuModel->nfeatures) {
            if (x86FeatureIsMigratable(cpuModel->features[i].name, map)) {
                i++;
            } else {
2019 2020 2021
                VIR_FREE(cpuModel->features[i].name);
                VIR_DELETE_ELEMENT_INPLACE(cpuModel->features, i,
                                           cpuModel->nfeatures);
2022 2023 2024 2025
            }
        }
    }

J
Jiri Denemark 已提交
2026 2027 2028
    if (vendor && VIR_STRDUP(cpu->vendor, vendor->name) < 0)
        goto cleanup;

2029 2030 2031 2032 2033
    sigs = x86FormatSignatures(model);

    VIR_DEBUG("Using CPU model %s (signatures %s) for CPU with signature %06lx",
              model->name, NULLSTR(sigs), (unsigned long)signature);

2034 2035
    VIR_STEAL_PTR(cpu->model, cpuModel->model);
    VIR_STEAL_PTR(cpu->features, cpuModel->features);
2036
    cpu->nfeatures = cpuModel->nfeatures;
2037 2038 2039
    cpuModel->nfeatures = 0;
    cpu->nfeatures_max = cpuModel->nfeatures_max;
    cpuModel->nfeatures_max = 0;
J
Jiri Denemark 已提交
2040 2041 2042

    ret = 0;

J
Jiri Denemark 已提交
2043
 cleanup:
2044
    virCPUDefFree(cpuModel);
2045
    virCPUx86DataClear(&data);
2046 2047
    virCPUx86DataClear(&copy);
    virCPUx86DataClear(&features);
J
Jiri Denemark 已提交
2048 2049 2050
    return ret;
}

2051 2052
static int
x86DecodeCPUData(virCPUDefPtr cpu,
2053
                 const virCPUData *data,
2054
                 virDomainCapsCPUModelsPtr models)
2055
{
2056
    return x86Decode(cpu, &data->data.x86, models, NULL, false);
2057
}
J
Jiri Denemark 已提交
2058

2059

2060 2061 2062
static int
x86EncodePolicy(virCPUx86Data *data,
                const virCPUDef *cpu,
J
Jiri Denemark 已提交
2063
                virCPUx86MapPtr map,
2064
                virCPUFeaturePolicy policy)
J
Jiri Denemark 已提交
2065
{
J
Jiri Denemark 已提交
2066
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
2067 2068

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

2071 2072
    *data = model->data;
    model->data.len = 0;
2073
    model->data.items = NULL;
J
Jiri Denemark 已提交
2074 2075
    x86ModelFree(model);

2076
    return 0;
J
Jiri Denemark 已提交
2077 2078 2079 2080
}


static int
J
Jiri Denemark 已提交
2081
x86Encode(virArch arch,
2082
          const virCPUDef *cpu,
2083 2084 2085 2086 2087 2088
          virCPUDataPtr *forced,
          virCPUDataPtr *required,
          virCPUDataPtr *optional,
          virCPUDataPtr *disabled,
          virCPUDataPtr *forbidden,
          virCPUDataPtr *vendor)
J
Jiri Denemark 已提交
2089
{
J
Jiri Denemark 已提交
2090
    virCPUx86MapPtr map = NULL;
2091 2092 2093 2094 2095 2096
    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 已提交
2097

2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
    if (forced)
        *forced = NULL;
    if (required)
        *required = NULL;
    if (optional)
        *optional = NULL;
    if (disabled)
        *disabled = NULL;
    if (forbidden)
        *forbidden = NULL;
    if (vendor)
        *vendor = NULL;

2111
    if (!(map = virCPUx86GetMap()))
J
Jiri Denemark 已提交
2112 2113
        goto error;

2114
    if (forced &&
2115 2116 2117
        (!(data_forced = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_forced->data.x86, cpu, map,
                         VIR_CPU_FEATURE_FORCE) < 0))
2118
        goto error;
J
Jiri Denemark 已提交
2119

2120
    if (required &&
2121 2122 2123
        (!(data_required = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_required->data.x86, cpu, map,
                         VIR_CPU_FEATURE_REQUIRE) < 0))
2124
        goto error;
J
Jiri Denemark 已提交
2125

2126
    if (optional &&
2127 2128 2129
        (!(data_optional = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_optional->data.x86, cpu, map,
                         VIR_CPU_FEATURE_OPTIONAL) < 0))
2130
        goto error;
J
Jiri Denemark 已提交
2131

2132
    if (disabled &&
2133 2134 2135
        (!(data_disabled = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_disabled->data.x86, cpu, map,
                         VIR_CPU_FEATURE_DISABLE) < 0))
2136
        goto error;
J
Jiri Denemark 已提交
2137

2138
    if (forbidden &&
2139 2140 2141
        (!(data_forbidden = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_forbidden->data.x86, cpu, map,
                         VIR_CPU_FEATURE_FORBID) < 0))
2142
        goto error;
J
Jiri Denemark 已提交
2143

J
Jiri Denemark 已提交
2144
    if (vendor) {
2145
        virCPUx86VendorPtr v = NULL;
J
Jiri Denemark 已提交
2146 2147

        if (cpu->vendor && !(v = x86VendorFind(map, cpu->vendor))) {
2148 2149
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("CPU vendor %s not found"), cpu->vendor);
J
Jiri Denemark 已提交
2150 2151 2152
            goto error;
        }

2153
        if (!(data_vendor = virCPUDataNew(arch)))
J
Jiri Denemark 已提交
2154 2155
            goto error;

2156
        if (v && virCPUx86DataAdd(data_vendor, &v->data) < 0)
2157 2158
            goto error;
    }
J
Jiri Denemark 已提交
2159

2160
    if (forced)
2161
        *forced = data_forced;
2162
    if (required)
2163
        *required = data_required;
2164
    if (optional)
2165
        *optional = data_optional;
2166
    if (disabled)
2167
        *disabled = data_disabled;
2168
    if (forbidden)
2169
        *forbidden = data_forbidden;
2170
    if (vendor)
2171 2172 2173 2174 2175
        *vendor = data_vendor;

    return 0;

 error:
J
Jiri Denemark 已提交
2176 2177 2178 2179 2180 2181
    virCPUx86DataFree(data_forced);
    virCPUx86DataFree(data_required);
    virCPUx86DataFree(data_optional);
    virCPUx86DataFree(data_disabled);
    virCPUx86DataFree(data_forbidden);
    virCPUx86DataFree(data_vendor);
2182
    return -1;
J
Jiri Denemark 已提交
2183 2184 2185
}


P
Pavel Hrdina 已提交
2186
#if defined(__i386__) || defined(__x86_64__)
J
Jiri Denemark 已提交
2187
static inline void
2188
cpuidCall(virCPUx86CPUID *cpuid)
J
Jiri Denemark 已提交
2189
{
2190
# if __x86_64__
2191
    asm("xor %%ebx, %%ebx;" /* clear the other registers as some cpuid */
2192
        "xor %%edx, %%edx;" /* functions may use them as additional arguments */
2193
        "cpuid;"
J
Jiri Denemark 已提交
2194 2195 2196 2197
        : "=a" (cpuid->eax),
          "=b" (cpuid->ebx),
          "=c" (cpuid->ecx),
          "=d" (cpuid->edx)
2198 2199
        : "a" (cpuid->eax_in),
          "c" (cpuid->ecx_in));
2200
# else
J
Jiri Denemark 已提交
2201 2202 2203 2204
    /* 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;"
2205
        "xor %%ebx, %%ebx;" /* clear the other registers as some cpuid */
2206
        "xor %%edx, %%edx;" /* functions may use them as additional arguments */
J
Jiri Denemark 已提交
2207 2208 2209 2210 2211 2212 2213
        "cpuid;"
        "mov %%ebx, %1;"
        "pop %%ebx;"
        : "=a" (cpuid->eax),
          "=r" (cpuid->ebx),
          "=c" (cpuid->ecx),
          "=d" (cpuid->edx)
2214 2215
        : "a" (cpuid->eax_in),
          "c" (cpuid->ecx_in)
J
Jiri Denemark 已提交
2216
        : "cc");
2217
# endif
J
Jiri Denemark 已提交
2218 2219 2220
}


2221 2222 2223 2224 2225
/* Leaf 0x04: deterministic cache parameters
 *
 * Sub leaf n+1 is invalid if eax[4:0] in sub leaf n equals 0.
 */
static int
2226
cpuidSetLeaf4(virCPUDataPtr data,
2227
              virCPUx86DataItemPtr subLeaf0)
2228
{
2229 2230
    virCPUx86DataItem item = *subLeaf0;
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2231

2232
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2233 2234
        return -1;

2235 2236 2237
    while (cpuid->eax & 0x1f) {
        cpuid->ecx_in++;
        cpuidCall(cpuid);
2238
        if (virCPUx86DataAdd(data, &item) < 0)
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
            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
2250
cpuidSetLeaf7(virCPUDataPtr data,
2251
              virCPUx86DataItemPtr subLeaf0)
2252
{
2253 2254
    virCPUx86DataItem item = CPUID(.eax_in = 0x7);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2255 2256
    uint32_t sub;

2257
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2258 2259
        return -1;

2260 2261 2262
    for (sub = 1; sub <= subLeaf0->cpuid.eax; sub++) {
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2263
        if (virCPUx86DataAdd(data, &item) < 0)
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
            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
2278
cpuidSetLeafB(virCPUDataPtr data,
2279
              virCPUx86DataItemPtr subLeaf0)
2280
{
2281 2282
    virCPUx86DataItem item = *subLeaf0;
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2283

2284
    while (cpuid->ecx & 0xff00) {
2285
        if (virCPUx86DataAdd(data, &item) < 0)
2286
            return -1;
2287 2288
        cpuid->ecx_in++;
        cpuidCall(cpuid);
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
    }
    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
2303
cpuidSetLeafD(virCPUDataPtr data,
2304
              virCPUx86DataItemPtr subLeaf0)
2305
{
2306 2307
    virCPUx86DataItem item = CPUID(.eax_in = 0xd);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2308 2309 2310 2311
    virCPUx86CPUID sub0;
    virCPUx86CPUID sub1;
    uint32_t sub;

2312
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2313 2314
        return -1;

2315 2316
    cpuid->ecx_in = 1;
    cpuidCall(cpuid);
2317
    if (virCPUx86DataAdd(data, &item) < 0)
2318 2319
        return -1;

2320 2321
    sub0 = subLeaf0->cpuid;
    sub1 = *cpuid;
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
    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;

2332 2333
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2334
        if (virCPUx86DataAdd(data, &item) < 0)
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
            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
2351
cpuidSetLeafResID(virCPUDataPtr data,
2352
                  virCPUx86DataItemPtr subLeaf0,
2353 2354
                  uint32_t res)
{
2355 2356
    virCPUx86DataItem item = CPUID(.eax_in = subLeaf0->cpuid.eax_in);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2357 2358
    uint32_t sub;

2359
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2360 2361 2362 2363 2364
        return -1;

    for (sub = 1; sub < 32; sub++) {
        if (!(res & (1 << sub)))
            continue;
2365 2366
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2367
        if (virCPUx86DataAdd(data, &item) < 0)
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
            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
2380
cpuidSetLeaf12(virCPUDataPtr data,
2381
               virCPUx86DataItemPtr subLeaf0)
2382
{
2383 2384
    virCPUx86DataItem item = CPUID(.eax_in = 0x7);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2385
    virCPUx86DataItemPtr leaf7;
2386

J
Jiri Denemark 已提交
2387
    if (!(leaf7 = virCPUx86DataGet(&data->data.x86, &item)) ||
2388
        !(leaf7->cpuid.ebx & (1 << 2)))
2389 2390
        return 0;

2391
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2392 2393
        return -1;

2394 2395 2396
    cpuid->eax_in = 0x12;
    cpuid->ecx_in = 1;
    cpuidCall(cpuid);
2397
    if (virCPUx86DataAdd(data, &item) < 0)
2398 2399
        return -1;

2400 2401 2402
    cpuid->ecx_in = 2;
    cpuidCall(cpuid);
    while (cpuid->eax & 0xf) {
2403
        if (virCPUx86DataAdd(data, &item) < 0)
2404
            return -1;
2405 2406
        cpuid->ecx_in++;
        cpuidCall(cpuid);
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
    }
    return 0;
}


/* Leaf 0x14: processor trace enumeration
 *
 * Sub leaf 0 reports the maximum supported sub leaf in eax.
 */
static int
2417
cpuidSetLeaf14(virCPUDataPtr data,
2418
               virCPUx86DataItemPtr subLeaf0)
2419
{
2420 2421
    virCPUx86DataItem item = CPUID(.eax_in = 0x14);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2422 2423
    uint32_t sub;

2424
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2425 2426
        return -1;

2427 2428 2429
    for (sub = 1; sub <= subLeaf0->cpuid.eax; sub++) {
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2430
        if (virCPUx86DataAdd(data, &item) < 0)
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
            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
2443
cpuidSetLeaf17(virCPUDataPtr data,
2444
               virCPUx86DataItemPtr subLeaf0)
2445
{
2446 2447
    virCPUx86DataItem item = CPUID(.eax_in = 0x17);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
2448 2449
    uint32_t sub;

2450
    if (subLeaf0->cpuid.eax < 3)
2451 2452
        return 0;

2453
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2454 2455
        return -1;

2456 2457 2458
    for (sub = 1; sub <= subLeaf0->cpuid.eax; sub++) {
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2459
        if (virCPUx86DataAdd(data, &item) < 0)
2460 2461 2462 2463 2464 2465
            return -1;
    }
    return 0;
}


J
Jiri Denemark 已提交
2466
static int
2467
cpuidSet(uint32_t base, virCPUDataPtr data)
J
Jiri Denemark 已提交
2468
{
2469
    int rc;
J
Jiri Denemark 已提交
2470
    uint32_t max;
2471
    uint32_t leaf;
2472 2473
    virCPUx86DataItem item = CPUID(.eax_in = base);
    virCPUx86CPUIDPtr cpuid = &item.cpuid;
J
Jiri Denemark 已提交
2474

2475 2476
    cpuidCall(cpuid);
    max = cpuid->eax;
J
Jiri Denemark 已提交
2477

2478
    for (leaf = base; leaf <= max; leaf++) {
2479 2480 2481
        cpuid->eax_in = leaf;
        cpuid->ecx_in = 0;
        cpuidCall(cpuid);
2482 2483 2484 2485 2486

        /* Handle CPUID leaves that depend on previously queried bits or
         * which provide additional sub leaves for ecx_in > 0
         */
        if (leaf == 0x4)
2487
            rc = cpuidSetLeaf4(data, &item);
2488
        else if (leaf == 0x7)
2489
            rc = cpuidSetLeaf7(data, &item);
2490
        else if (leaf == 0xb)
2491
            rc = cpuidSetLeafB(data, &item);
2492
        else if (leaf == 0xd)
2493
            rc = cpuidSetLeafD(data, &item);
2494
        else if (leaf == 0xf)
2495
            rc = cpuidSetLeafResID(data, &item, cpuid->edx);
2496
        else if (leaf == 0x10)
2497
            rc = cpuidSetLeafResID(data, &item, cpuid->ebx);
2498
        else if (leaf == 0x12)
2499
            rc = cpuidSetLeaf12(data, &item);
2500
        else if (leaf == 0x14)
2501
            rc = cpuidSetLeaf14(data, &item);
2502
        else if (leaf == 0x17)
2503
            rc = cpuidSetLeaf17(data, &item);
2504
        else
2505
            rc = virCPUx86DataAdd(data, &item);
2506 2507

        if (rc < 0)
2508
            return -1;
J
Jiri Denemark 已提交
2509 2510
    }

2511
    return 0;
J
Jiri Denemark 已提交
2512 2513 2514
}


2515
static int
2516
virCPUx86GetHost(virCPUDefPtr cpu,
2517
                 virDomainCapsCPUModelsPtr models)
J
Jiri Denemark 已提交
2518
{
2519
    virCPUDataPtr cpuData = NULL;
2520
    int ret = -1;
J
Jiri Denemark 已提交
2521

2522 2523 2524
    if (virCPUx86DriverInitialize() < 0)
        goto cleanup;

2525 2526
    if (!(cpuData = virCPUDataNew(archs[0])))
        goto cleanup;
J
Jiri Denemark 已提交
2527

2528 2529 2530
    if (cpuidSet(CPUX86_BASIC, cpuData) < 0 ||
        cpuidSet(CPUX86_EXTENDED, cpuData) < 0)
        goto cleanup;
2531

2532
    ret = x86DecodeCPUData(cpu, cpuData, models);
2533
    cpu->microcodeVersion = virHostCPUGetMicrocodeVersion();
J
Jiri Denemark 已提交
2534

2535
 cleanup:
J
Jiri Denemark 已提交
2536
    virCPUx86DataFree(cpuData);
2537
    return ret;
J
Jiri Denemark 已提交
2538 2539 2540 2541
}
#endif


2542
static virCPUDefPtr
2543 2544 2545
virCPUx86Baseline(virCPUDefPtr *cpus,
                  unsigned int ncpus,
                  virDomainCapsCPUModelsPtr models,
2546
                  const char **features,
2547
                  bool migratable)
2548
{
J
Jiri Denemark 已提交
2549
    virCPUx86MapPtr map = NULL;
J
Jiri Denemark 已提交
2550
    virCPUx86ModelPtr base_model = NULL;
2551
    virCPUDefPtr cpu = NULL;
2552
    size_t i;
2553
    virCPUx86VendorPtr vendor = NULL;
J
Jiri Denemark 已提交
2554
    virCPUx86ModelPtr model = NULL;
2555
    bool outputVendor = true;
2556 2557
    const char *modelName;
    bool matchingNames = true;
2558
    virCPUDataPtr featData = NULL;
2559

2560
    if (!(map = virCPUx86GetMap()))
2561 2562
        goto error;

2563
    if (!(base_model = x86ModelFromCPU(cpus[0], map, -1)))
2564 2565
        goto error;

2566
    if (VIR_ALLOC(cpu) < 0)
2567
        goto error;
2568

2569 2570
    cpu->type = VIR_CPU_TYPE_GUEST;
    cpu->match = VIR_CPU_MATCH_EXACT;
2571

2572
    if (!cpus[0]->vendor) {
2573
        outputVendor = false;
2574
    } else if (!(vendor = x86VendorFind(map, cpus[0]->vendor))) {
2575 2576
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unknown CPU vendor %s"), cpus[0]->vendor);
J
Jiri Denemark 已提交
2577 2578 2579
        goto error;
    }

2580
    modelName = cpus[0]->model;
2581
    for (i = 1; i < ncpus; i++) {
J
Jiri Denemark 已提交
2582 2583
        const char *vn = NULL;

2584 2585 2586 2587 2588 2589 2590 2591 2592
        if (matchingNames && cpus[i]->model) {
            if (!modelName) {
                modelName = cpus[i]->model;
            } else if (STRNEQ(modelName, cpus[i]->model)) {
                modelName = NULL;
                matchingNames = false;
            }
        }

2593
        if (!(model = x86ModelFromCPU(cpus[i], map, -1)))
2594 2595
            goto error;

J
Jiri Denemark 已提交
2596 2597
        if (cpus[i]->vendor && model->vendor &&
            STRNEQ(cpus[i]->vendor, model->vendor->name)) {
2598 2599 2600
            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 已提交
2601 2602 2603
            goto error;
        }

2604
        if (cpus[i]->vendor) {
J
Jiri Denemark 已提交
2605
            vn = cpus[i]->vendor;
2606
        } else {
2607 2608 2609 2610
            outputVendor = false;
            if (model->vendor)
                vn = model->vendor->name;
        }
J
Jiri Denemark 已提交
2611 2612 2613 2614

        if (vn) {
            if (!vendor) {
                if (!(vendor = x86VendorFind(map, vn))) {
2615 2616
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("Unknown CPU vendor %s"), vn);
J
Jiri Denemark 已提交
2617 2618 2619
                    goto error;
                }
            } else if (STRNEQ(vendor->name, vn)) {
2620 2621
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("CPU vendors do not match"));
J
Jiri Denemark 已提交
2622 2623 2624 2625
                goto error;
            }
        }

2626
        x86DataIntersect(&base_model->data, &model->data);
2627
        x86ModelFree(model);
J
Jiri Denemark 已提交
2628
        model = NULL;
2629 2630
    }

2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
    if (features) {
        virCPUx86FeaturePtr feat;

        if (!(featData = virCPUDataNew(archs[0])))
            goto cleanup;

        for (i = 0; features[i]; i++) {
            if ((feat = x86FeatureFind(map, features[i])) &&
                x86DataAdd(&featData->data.x86, &feat->data) < 0)
                goto cleanup;
        }

        x86DataIntersect(&base_model->data, &featData->data.x86);
    }

2646
    if (x86DataIsEmpty(&base_model->data)) {
2647 2648
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("CPUs are incompatible"));
2649 2650 2651
        goto error;
    }

2652
    if (vendor &&
2653
        virCPUx86DataAddItem(&base_model->data, &vendor->data) < 0)
2654
        goto error;
J
Jiri Denemark 已提交
2655

2656
    if (x86Decode(cpu, &base_model->data, models, modelName, migratable) < 0)
2657 2658
        goto error;

2659 2660 2661
    if (STREQ_NULLABLE(cpu->model, modelName))
        cpu->fallback = VIR_CPU_FALLBACK_FORBID;

2662 2663 2664
    if (!outputVendor)
        VIR_FREE(cpu->vendor);

2665
 cleanup:
2666
    x86ModelFree(base_model);
2667
    virCPUx86DataFree(featData);
2668 2669 2670

    return cpu;

2671
 error:
J
Jiri Denemark 已提交
2672
    x86ModelFree(model);
2673 2674 2675 2676 2677 2678
    virCPUDefFree(cpu);
    cpu = NULL;
    goto cleanup;
}


2679
static int
J
Jiri Denemark 已提交
2680
x86UpdateHostModel(virCPUDefPtr guest,
2681
                   const virCPUDef *host)
2682
{
J
Jiri Denemark 已提交
2683
    virCPUDefPtr updated = NULL;
2684
    size_t i;
J
Jiri Denemark 已提交
2685
    int ret = -1;
2686

J
Jiri Denemark 已提交
2687
    if (!(updated = virCPUDefCopyWithoutModel(host)))
2688 2689
        goto cleanup;

J
Jiri Denemark 已提交
2690 2691
    updated->type = VIR_CPU_TYPE_GUEST;
    updated->mode = VIR_CPU_MODE_CUSTOM;
2692
    if (virCPUDefCopyModel(updated, host, true) < 0)
J
Jiri Denemark 已提交
2693
        goto cleanup;
2694

J
Jiri Denemark 已提交
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
    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)
2705 2706 2707
            goto cleanup;
    }

2708 2709
    virCPUDefStealModel(guest, updated,
                        guest->mode == VIR_CPU_MODE_CUSTOM);
J
Jiri Denemark 已提交
2710 2711
    guest->mode = VIR_CPU_MODE_CUSTOM;
    guest->match = VIR_CPU_MATCH_EXACT;
2712 2713
    ret = 0;

2714
 cleanup:
J
Jiri Denemark 已提交
2715
    virCPUDefFree(updated);
2716 2717 2718
    return ret;
}

2719 2720

static int
J
Jiri Denemark 已提交
2721 2722
virCPUx86Update(virCPUDefPtr guest,
                const virCPUDef *host)
2723
{
J
Jiri Denemark 已提交
2724
    virCPUx86ModelPtr model = NULL;
J
Jiri Denemark 已提交
2725
    virCPUx86MapPtr map;
2726
    int ret = -1;
J
Jiri Denemark 已提交
2727
    size_t i;
2728

J
Jiri Denemark 已提交
2729 2730 2731 2732 2733
    if (!host) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unknown host CPU model"));
        return -1;
    }
2734

J
Jiri Denemark 已提交
2735 2736
    if (!(map = virCPUx86GetMap()))
        return -1;
2737

J
Jiri Denemark 已提交
2738
    if (!(model = x86ModelFromCPU(host, map, -1)))
2739
        goto cleanup;
2740

J
Jiri Denemark 已提交
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
    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;
2751 2752
        }
    }
2753

J
Jiri Denemark 已提交
2754 2755
    if (guest->mode == VIR_CPU_MODE_HOST_MODEL ||
        guest->match == VIR_CPU_MATCH_MINIMUM)
2756
        ret = x86UpdateHostModel(guest, host);
J
Jiri Denemark 已提交
2757 2758
    else
        ret = 0;
2759 2760

 cleanup:
J
Jiri Denemark 已提交
2761
    x86ModelFree(model);
2762
    return ret;
2763 2764 2765
}


2766 2767 2768 2769 2770 2771 2772 2773 2774
static int
virCPUx86UpdateLive(virCPUDefPtr cpu,
                    virCPUDataPtr dataEnabled,
                    virCPUDataPtr dataDisabled)
{
    virCPUx86MapPtr map;
    virCPUx86ModelPtr model = NULL;
    virCPUx86Data enabled = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data disabled = VIR_CPU_X86_DATA_INIT;
2775 2776 2777 2778
    virBuffer bufAdded = VIR_BUFFER_INITIALIZER;
    virBuffer bufRemoved = VIR_BUFFER_INITIALIZER;
    char *added = NULL;
    char *removed = NULL;
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
    size_t i;
    int ret = -1;

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

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

    if (dataEnabled &&
        x86DataCopy(&enabled, &dataEnabled->data.x86) < 0)
        goto cleanup;

    if (dataDisabled &&
        x86DataCopy(&disabled, &dataDisabled->data.x86) < 0)
        goto cleanup;

    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];

2799 2800
        if (x86DataIsSubset(&enabled, &feature->data) &&
            !x86DataIsSubset(&model->data, &feature->data)) {
2801 2802 2803 2804 2805
            VIR_DEBUG("Feature '%s' enabled by the hypervisor", feature->name);
            if (cpu->check == VIR_CPU_CHECK_FULL)
                virBufferAsprintf(&bufAdded, "%s,", feature->name);
            else if (virCPUDefUpdateFeature(cpu, feature->name,
                                            VIR_CPU_FEATURE_REQUIRE) < 0)
2806 2807 2808
                goto cleanup;
        }

2809 2810 2811
        if (x86DataIsSubset(&disabled, &feature->data) ||
            (x86DataIsSubset(&model->data, &feature->data) &&
             !x86DataIsSubset(&enabled, &feature->data))) {
2812 2813 2814 2815 2816
            VIR_DEBUG("Feature '%s' disabled by the hypervisor", feature->name);
            if (cpu->check == VIR_CPU_CHECK_FULL)
                virBufferAsprintf(&bufRemoved, "%s,", feature->name);
            else if (virCPUDefUpdateFeature(cpu, feature->name,
                                            VIR_CPU_FEATURE_DISABLE) < 0)
2817 2818 2819 2820
                goto cleanup;
        }
    }

2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
    virBufferTrim(&bufAdded, ",", -1);
    virBufferTrim(&bufRemoved, ",", -1);

    if (virBufferCheckError(&bufAdded) < 0 ||
        virBufferCheckError(&bufRemoved) < 0)
        goto cleanup;

    added = virBufferContentAndReset(&bufAdded);
    removed = virBufferContentAndReset(&bufRemoved);

    if (added || removed) {
        if (added && removed)
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("guest CPU doesn't match specification: "
                             "extra features: %s, missing features: %s"),
                           added, removed);
        else if (added)
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("guest CPU doesn't match specification: "
                             "extra features: %s"),
                           added);
        else
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("guest CPU doesn't match specification: "
                             "missing features: %s"),
                           removed);
        goto cleanup;
    }

    if (cpu->check == VIR_CPU_CHECK_FULL &&
        !x86DataIsEmpty(&disabled)) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("guest CPU doesn't match specification"));
        goto cleanup;
    }

2857 2858 2859 2860 2861 2862
    ret = 0;

 cleanup:
    x86ModelFree(model);
    virCPUx86DataClear(&enabled);
    virCPUx86DataClear(&disabled);
2863 2864 2865 2866
    VIR_FREE(added);
    VIR_FREE(removed);
    virBufferFreeAndReset(&bufAdded);
    virBufferFreeAndReset(&bufRemoved);
2867 2868 2869 2870
    return ret;
}


2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
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;
}


2893
static int
2894 2895
virCPUx86DataCheckFeature(const virCPUData *data,
                          const char *name)
D
Daniel P. Berrange 已提交
2896
{
J
Jiri Denemark 已提交
2897
    virCPUx86MapPtr map;
D
Daniel P. Berrange 已提交
2898

2899
    if (!(map = virCPUx86GetMap()))
D
Daniel P. Berrange 已提交
2900 2901
        return -1;

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

2905
static int
J
Jiri Denemark 已提交
2906
virCPUx86GetModels(char ***models)
2907
{
J
Jiri Denemark 已提交
2908
    virCPUx86MapPtr map;
2909
    size_t i;
2910 2911 2912 2913

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

2914 2915 2916
    if (models) {
        if (VIR_ALLOC_N(*models, map->nmodels + 1) < 0)
            goto error;
2917

2918 2919
        for (i = 0; i < map->nmodels; i++) {
            if (VIR_STRDUP((*models)[i], map->models[i]->name) < 0)
2920 2921
                goto error;
        }
2922 2923
    }

2924
    return map->nmodels;
2925 2926

 error:
2927
    if (models) {
2928
        virStringListFree(*models);
2929 2930
        *models = NULL;
    }
2931 2932 2933
    return -1;
}

2934

J
Jiri Denemark 已提交
2935 2936
static int
virCPUx86Translate(virCPUDefPtr cpu,
2937
                   virDomainCapsCPUModelsPtr models)
J
Jiri Denemark 已提交
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
{
    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 &&
2952
        virCPUx86DataAddItem(&model->data, &model->vendor->data) < 0)
J
Jiri Denemark 已提交
2953 2954
        goto cleanup;

2955 2956
    if (model->signatures &&
        x86DataAddSignature(&model->data, model->signatures[0]) < 0)
J
Jiri Denemark 已提交
2957 2958 2959 2960 2961
        goto cleanup;

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

2962
    if (x86Decode(translated, &model->data, models, NULL, false) < 0)
J
Jiri Denemark 已提交
2963 2964 2965 2966 2967 2968 2969 2970
        goto cleanup;

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

2971
    virCPUDefStealModel(cpu, translated, true);
J
Jiri Denemark 已提交
2972 2973 2974 2975 2976 2977 2978 2979 2980
    ret = 0;

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


2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
static int
virCPUx86ExpandFeatures(virCPUDefPtr cpu)
{
    virCPUx86MapPtr map;
    virCPUDefPtr expanded = NULL;
    virCPUx86ModelPtr model = NULL;
    bool host = cpu->type == VIR_CPU_TYPE_HOST;
    size_t i;
    int ret = -1;

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

    if (!(expanded = virCPUDefCopy(cpu)))
        goto cleanup;

    virCPUDefFreeFeatures(expanded);

    if (!(model = x86ModelFind(map, cpu->model))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown CPU model %s"), cpu->model);
        goto cleanup;
    }

    if (!(model = x86ModelCopy(model)) ||
        x86DataToCPUFeatures(expanded, host ? -1 : VIR_CPU_FEATURE_REQUIRE,
                             &model->data, map) < 0)
        goto cleanup;

    for (i = 0; i < cpu->nfeatures; i++) {
        virCPUFeatureDefPtr f = cpu->features + i;

        if (!host &&
            f->policy != VIR_CPU_FEATURE_REQUIRE &&
            f->policy != VIR_CPU_FEATURE_DISABLE)
            continue;

        if (virCPUDefUpdateFeature(expanded, f->name, f->policy) < 0)
            goto cleanup;
    }

    virCPUDefFreeModel(cpu);

    ret = virCPUDefCopyModel(cpu, expanded, false);

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


3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
static virCPUDefPtr
virCPUx86CopyMigratable(virCPUDefPtr cpu)
{
    virCPUDefPtr copy;
    virCPUx86MapPtr map;

    if (!(map = virCPUx86GetMap()))
        return NULL;

    if (!(copy = virCPUDefCopyWithoutModel(cpu)))
        return NULL;

    if (virCPUDefCopyModelFilter(copy, cpu, false,
                                 x86FeatureIsMigratable, map) < 0)
        goto error;

    return copy;

 error:
    virCPUDefFree(copy);
    return NULL;
}


3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078
static int
virCPUx86ValidateFeatures(virCPUDefPtr cpu)
{
    virCPUx86MapPtr map;
    size_t i;

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

    for (i = 0; i < cpu->nfeatures; i++) {
        if (!x86FeatureFind(map, cpu->features[i].name)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown CPU feature: %s"),
                           cpu->features[i].name);
            return -1;
        }
    }

    return 0;
}


3079
int
3080 3081
virCPUx86DataAdd(virCPUDataPtr cpuData,
                 const virCPUx86DataItem *item)
3082
{
3083
    return virCPUx86DataAddItem(&cpuData->data.x86, item);
3084 3085 3086
}


3087 3088 3089
int
virCPUx86DataSetSignature(virCPUDataPtr cpuData,
                          unsigned int family,
3090 3091
                          unsigned int model,
                          unsigned int stepping)
3092
{
3093
    uint32_t signature = x86MakeSignature(family, model, stepping);
3094 3095 3096 3097 3098

    return x86DataAddSignature(&cpuData->data.x86, signature);
}


3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
uint32_t
virCPUx86DataGetSignature(virCPUDataPtr cpuData,
                          unsigned int *family,
                          unsigned int *model,
                          unsigned int *stepping)
{
    x86DataToSignatureFull(&cpuData->data.x86, family, model, stepping);

    return x86MakeSignature(*family, *model, *stepping);
}


3111 3112 3113 3114
int
virCPUx86DataSetVendor(virCPUDataPtr cpuData,
                       const char *vendor)
{
3115
    virCPUx86DataItem item = CPUID(0);
3116

3117
    if (virCPUx86VendorToData(vendor, &item) < 0)
3118 3119
        return -1;

3120
    return virCPUx86DataAdd(cpuData, &item);
3121 3122 3123
}


3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145
int
virCPUx86DataAddFeature(virCPUDataPtr cpuData,
                        const char *name)
{
    virCPUx86FeaturePtr feature;
    virCPUx86MapPtr map;

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

    /* ignore unknown features */
    if (!(feature = x86FeatureFind(map, name)) &&
        !(feature = x86FeatureFindInternal(name)))
        return 0;

    if (x86DataAdd(&cpuData->data.x86, &feature->data) < 0)
        return -1;

    return 0;
}


J
Jiri Denemark 已提交
3146 3147 3148 3149
struct cpuArchDriver cpuDriverX86 = {
    .name = "x86",
    .arch = archs,
    .narch = ARRAY_CARDINALITY(archs),
J
Jiri Denemark 已提交
3150
    .compare    = virCPUx86Compare,
3151
    .decode     = x86DecodeCPUData,
J
Jiri Denemark 已提交
3152
    .encode     = x86Encode,
J
Jiri Denemark 已提交
3153
    .dataFree   = virCPUx86DataFree,
P
Pavel Hrdina 已提交
3154
#if defined(__i386__) || defined(__x86_64__)
3155
    .getHost    = virCPUx86GetHost,
J
Jiri Denemark 已提交
3156
#endif
3157
    .baseline   = virCPUx86Baseline,
J
Jiri Denemark 已提交
3158
    .update     = virCPUx86Update,
3159
    .updateLive = virCPUx86UpdateLive,
3160
    .checkFeature = virCPUx86CheckFeature,
3161
    .dataCheckFeature = virCPUx86DataCheckFeature,
J
Jiri Denemark 已提交
3162
    .dataFormat = virCPUx86DataFormat,
J
Jiri Denemark 已提交
3163
    .dataParse  = virCPUx86DataParse,
J
Jiri Denemark 已提交
3164
    .getModels  = virCPUx86GetModels,
J
Jiri Denemark 已提交
3165
    .translate  = virCPUx86Translate,
3166
    .expandFeatures = virCPUx86ExpandFeatures,
3167
    .copyMigratable = virCPUx86CopyMigratable,
3168
    .validateFeatures = virCPUx86ValidateFeatures,
J
Jiri Denemark 已提交
3169
};