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

#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 60
#define CPUID(...) \
    { .type = VIR_CPU_X86_DATA_CPUID, \
      .data = { .cpuid = {__VA_ARGS__} } }
61

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

67 68 69 70
#define KVM_FEATURE(Name) \
    { \
        .name = (char *) Name, \
        .data = { \
71
            .len = G_N_ELEMENTS(Name ## _data), \
72
            .items = Name ## _data, \
73
        } \
74 75 76
    }

KVM_FEATURE_DEF(VIR_CPU_x86_KVM_PV_UNHALT,
77
                0x40000001, 0x00000080, 0x0);
78 79

KVM_FEATURE_DEF(VIR_CPU_x86_HV_RUNTIME,
80
                0x40000003, 0x00000001, 0x0);
81
KVM_FEATURE_DEF(VIR_CPU_x86_HV_SYNIC,
82
                0x40000003, 0x00000004, 0x0);
83
KVM_FEATURE_DEF(VIR_CPU_x86_HV_STIMER,
84
                0x40000003, 0x00000008, 0x0);
85
KVM_FEATURE_DEF(VIR_CPU_x86_HV_RELAXED,
86
                0x40000003, 0x00000020, 0x0);
87
KVM_FEATURE_DEF(VIR_CPU_x86_HV_VAPIC,
88
                0x40000003, 0x00000030, 0x0);
89
KVM_FEATURE_DEF(VIR_CPU_x86_HV_VPINDEX,
90
                0x40000003, 0x00000040, 0x0);
91
KVM_FEATURE_DEF(VIR_CPU_x86_HV_RESET,
92
                0x40000003, 0x00000080, 0x0);
93
KVM_FEATURE_DEF(VIR_CPU_x86_HV_FREQUENCIES,
94
                0x40000003, 0x00000800, 0x0);
95
KVM_FEATURE_DEF(VIR_CPU_x86_HV_REENLIGHTENMENT,
96
                0x40000003, 0x00002000, 0x0);
97
KVM_FEATURE_DEF(VIR_CPU_x86_HV_TLBFLUSH,
98
                0x40000004, 0x00000004, 0x0);
99
KVM_FEATURE_DEF(VIR_CPU_x86_HV_IPI,
100
                0x40000004, 0x00000400, 0x0);
101
KVM_FEATURE_DEF(VIR_CPU_x86_HV_EVMCS,
102
                0x40000004, 0x00004000, 0x0);
103 104
KVM_FEATURE_DEF(VIR_CPU_x86_HV_STIMER_DIRECT,
                0x40000003, 0x0, 0x00080000);
105 106 107 108

static virCPUx86Feature x86_kvm_features[] =
{
    KVM_FEATURE(VIR_CPU_x86_KVM_PV_UNHALT),
109 110 111 112 113 114 115 116 117 118 119 120
    KVM_FEATURE(VIR_CPU_x86_HV_RUNTIME),
    KVM_FEATURE(VIR_CPU_x86_HV_SYNIC),
    KVM_FEATURE(VIR_CPU_x86_HV_STIMER),
    KVM_FEATURE(VIR_CPU_x86_HV_RELAXED),
    KVM_FEATURE(VIR_CPU_x86_HV_VAPIC),
    KVM_FEATURE(VIR_CPU_x86_HV_VPINDEX),
    KVM_FEATURE(VIR_CPU_x86_HV_RESET),
    KVM_FEATURE(VIR_CPU_x86_HV_FREQUENCIES),
    KVM_FEATURE(VIR_CPU_x86_HV_REENLIGHTENMENT),
    KVM_FEATURE(VIR_CPU_x86_HV_TLBFLUSH),
    KVM_FEATURE(VIR_CPU_x86_HV_IPI),
    KVM_FEATURE(VIR_CPU_x86_HV_EVMCS),
121
    KVM_FEATURE(VIR_CPU_x86_HV_STIMER_DIRECT),
122 123
};

J
Jiri Denemark 已提交
124 125 126
typedef struct _virCPUx86Model virCPUx86Model;
typedef virCPUx86Model *virCPUx86ModelPtr;
struct _virCPUx86Model {
J
Jiri Denemark 已提交
127
    char *name;
128
    virCPUx86VendorPtr vendor;
129 130
    size_t nsignatures;
    uint32_t *signatures;
131
    virCPUx86Data data;
J
Jiri Denemark 已提交
132 133
};

J
Jiri Denemark 已提交
134 135 136
typedef struct _virCPUx86Map virCPUx86Map;
typedef virCPUx86Map *virCPUx86MapPtr;
struct _virCPUx86Map {
137 138
    size_t nvendors;
    virCPUx86VendorPtr *vendors;
139 140
    size_t nfeatures;
    virCPUx86FeaturePtr *features;
141 142
    size_t nmodels;
    virCPUx86ModelPtr *models;
143 144
    size_t nblockers;
    virCPUx86FeaturePtr *migrate_blockers;
J
Jiri Denemark 已提交
145 146
};

J
Jiri Denemark 已提交
147
static virCPUx86MapPtr cpuMap;
148

149 150
int virCPUx86DriverOnceInit(void);
VIR_ONCE_GLOBAL_INIT(virCPUx86Driver);
151

J
Jiri Denemark 已提交
152

153
typedef enum {
J
Jiri Denemark 已提交
154 155 156 157
    SUBSET,
    EQUAL,
    SUPERSET,
    UNRELATED
158
} virCPUx86CompareResult;
J
Jiri Denemark 已提交
159 160


161 162 163
typedef struct _virCPUx86DataIterator virCPUx86DataIterator;
typedef virCPUx86DataIterator *virCPUx86DataIteratorPtr;
struct _virCPUx86DataIterator {
164
    const virCPUx86Data *data;
J
Jiri Denemark 已提交
165 166
    int pos;
};
J
Jiri Denemark 已提交
167 168


169 170 171 172 173 174 175
static void
virCPUx86DataIteratorInit(virCPUx86DataIteratorPtr iterator,
                          const virCPUx86Data *data)
{
    virCPUx86DataIterator iter = { data, -1 };
    *iterator = iter;
}
J
Jiri Denemark 已提交
176 177


178
static bool
179 180
virCPUx86DataItemMatch(const virCPUx86DataItem *item1,
                       const virCPUx86DataItem *item2)
J
Jiri Denemark 已提交
181
{
182 183
    const virCPUx86CPUID *cpuid1;
    const virCPUx86CPUID *cpuid2;
184 185
    const virCPUx86MSR *msr1;
    const virCPUx86MSR *msr2;
186 187 188 189 190 191 192 193 194 195

    switch (item1->type) {
    case VIR_CPU_X86_DATA_CPUID:
        cpuid1 = &item1->data.cpuid;
        cpuid2 = &item2->data.cpuid;
        return (cpuid1->eax == cpuid2->eax &&
                cpuid1->ebx == cpuid2->ebx &&
                cpuid1->ecx == cpuid2->ecx &&
                cpuid1->edx == cpuid2->edx);

196 197 198 199 200 201
    case VIR_CPU_X86_DATA_MSR:
        msr1 = &item1->data.msr;
        msr2 = &item2->data.msr;
        return (msr1->eax == msr2->eax &&
                msr1->edx == msr2->edx);

202 203 204 205
    case VIR_CPU_X86_DATA_NONE:
    default:
        return false;
    }
J
Jiri Denemark 已提交
206 207 208
}


209
static bool
210 211
virCPUx86DataItemMatchMasked(const virCPUx86DataItem *item,
                             const virCPUx86DataItem *mask)
J
Jiri Denemark 已提交
212
{
213 214
    const virCPUx86CPUID *cpuid;
    const virCPUx86CPUID *cpuidMask;
215 216
    const virCPUx86MSR *msr;
    const virCPUx86MSR *msrMask;
217 218 219 220 221 222 223 224 225 226

    switch (item->type) {
    case VIR_CPU_X86_DATA_CPUID:
        cpuid = &item->data.cpuid;
        cpuidMask = &mask->data.cpuid;
        return ((cpuid->eax & cpuidMask->eax) == cpuidMask->eax &&
                (cpuid->ebx & cpuidMask->ebx) == cpuidMask->ebx &&
                (cpuid->ecx & cpuidMask->ecx) == cpuidMask->ecx &&
                (cpuid->edx & cpuidMask->edx) == cpuidMask->edx);

227 228 229 230 231 232
    case VIR_CPU_X86_DATA_MSR:
        msr = &item->data.msr;
        msrMask = &mask->data.msr;
        return ((msr->eax & msrMask->eax) == msrMask->eax &&
                (msr->edx & msrMask->edx) == msrMask->edx);

233 234 235 236
    case VIR_CPU_X86_DATA_NONE:
    default:
        return false;
    }
J
Jiri Denemark 已提交
237 238 239
}


J
Jiri Denemark 已提交
240
static void
241 242
virCPUx86DataItemSetBits(virCPUx86DataItemPtr item,
                         const virCPUx86DataItem *mask)
J
Jiri Denemark 已提交
243
{
244 245
    virCPUx86CPUIDPtr cpuid;
    const virCPUx86CPUID *cpuidMask;
246 247
    virCPUx86MSRPtr msr;
    const virCPUx86MSR *msrMask;
248

249 250 251
    if (!mask)
        return;

252 253 254 255 256 257 258 259 260 261
    switch (item->type) {
    case VIR_CPU_X86_DATA_CPUID:
        cpuid = &item->data.cpuid;
        cpuidMask = &mask->data.cpuid;
        cpuid->eax |= cpuidMask->eax;
        cpuid->ebx |= cpuidMask->ebx;
        cpuid->ecx |= cpuidMask->ecx;
        cpuid->edx |= cpuidMask->edx;
        break;

262 263 264 265 266 267 268
    case VIR_CPU_X86_DATA_MSR:
        msr = &item->data.msr;
        msrMask = &mask->data.msr;
        msr->eax |= msrMask->eax;
        msr->edx |= msrMask->edx;
        break;

269 270 271 272
    case VIR_CPU_X86_DATA_NONE:
    default:
        break;
    }
J
Jiri Denemark 已提交
273 274 275
}


J
Jiri Denemark 已提交
276
static void
277 278
virCPUx86DataItemClearBits(virCPUx86DataItemPtr item,
                           const virCPUx86DataItem *mask)
J
Jiri Denemark 已提交
279
{
280 281
    virCPUx86CPUIDPtr cpuid;
    const virCPUx86CPUID *cpuidMask;
282 283
    virCPUx86MSRPtr msr;
    const virCPUx86MSR *msrMask;
284

285 286 287
    if (!mask)
        return;

288 289 290 291 292 293 294 295 296 297
    switch (item->type) {
    case VIR_CPU_X86_DATA_CPUID:
        cpuid = &item->data.cpuid;
        cpuidMask = &mask->data.cpuid;
        cpuid->eax &= ~cpuidMask->eax;
        cpuid->ebx &= ~cpuidMask->ebx;
        cpuid->ecx &= ~cpuidMask->ecx;
        cpuid->edx &= ~cpuidMask->edx;
        break;

298 299 300 301 302 303 304
    case VIR_CPU_X86_DATA_MSR:
        msr = &item->data.msr;
        msrMask = &mask->data.msr;
        msr->eax &= ~msrMask->eax;
        msr->edx &= ~msrMask->edx;
        break;

305 306 307 308
    case VIR_CPU_X86_DATA_NONE:
    default:
        break;
    }
J
Jiri Denemark 已提交
309 310 311
}


J
Jiri Denemark 已提交
312
static void
313 314
virCPUx86DataItemAndBits(virCPUx86DataItemPtr item,
                         const virCPUx86DataItem *mask)
315
{
316 317
    virCPUx86CPUIDPtr cpuid;
    const virCPUx86CPUID *cpuidMask;
318 319
    virCPUx86MSRPtr msr;
    const virCPUx86MSR *msrMask;
320

321 322 323
    if (!mask)
        return;

324 325 326 327 328 329 330 331 332 333
    switch (item->type) {
    case VIR_CPU_X86_DATA_CPUID:
        cpuid = &item->data.cpuid;
        cpuidMask = &mask->data.cpuid;
        cpuid->eax &= cpuidMask->eax;
        cpuid->ebx &= cpuidMask->ebx;
        cpuid->ecx &= cpuidMask->ecx;
        cpuid->edx &= cpuidMask->edx;
        break;

334 335 336 337 338 339 340
    case VIR_CPU_X86_DATA_MSR:
        msr = &item->data.msr;
        msrMask = &mask->data.msr;
        msr->eax &= msrMask->eax;
        msr->edx &= msrMask->edx;
        break;

341 342 343 344
    case VIR_CPU_X86_DATA_NONE:
    default:
        break;
    }
345 346
}

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

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;
367
    size_t count = G_N_ELEMENTS(x86_kvm_features);
368 369 370 371 372 373 374 375 376 377

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

    return NULL;
}


378
static int
379
virCPUx86DataSorter(const void *a, const void *b)
380
{
381 382
    virCPUx86DataItemPtr da = (virCPUx86DataItemPtr) a;
    virCPUx86DataItemPtr db = (virCPUx86DataItemPtr) b;
383

384
    if (da->type > db->type)
385
        return 1;
386
    else if (da->type < db->type)
387 388
        return -1;

389 390 391 392 393 394 395 396 397 398 399 400 401 402
    switch (da->type) {
    case VIR_CPU_X86_DATA_CPUID:
        if (da->data.cpuid.eax_in > db->data.cpuid.eax_in)
            return 1;
        else if (da->data.cpuid.eax_in < db->data.cpuid.eax_in)
            return -1;

        if (da->data.cpuid.ecx_in > db->data.cpuid.ecx_in)
            return 1;
        else if (da->data.cpuid.ecx_in < db->data.cpuid.ecx_in)
            return -1;

        break;

403 404 405 406 407 408 409 410
    case VIR_CPU_X86_DATA_MSR:
        if (da->data.msr.index > db->data.msr.index)
            return 1;
        else if (da->data.msr.index < db->data.msr.index)
            return -1;

        break;

411 412 413 414
    case VIR_CPU_X86_DATA_NONE:
    default:
        break;
    }
415

416 417 418
    return 0;
}

419 420 421 422 423 424 425
static int
virCPUx86DataItemCmp(const virCPUx86DataItem *item1,
                     const virCPUx86DataItem *item2)
{
    return virCPUx86DataSorter(item1, item2);
}

426

427
/* skips all zero CPUID leaves */
428
static virCPUx86DataItemPtr
429
virCPUx86DataNext(virCPUx86DataIteratorPtr iterator)
J
Jiri Denemark 已提交
430
{
431
    const virCPUx86Data *data = iterator->data;
432
    virCPUx86DataItem zero = { 0 };
J
Jiri Denemark 已提交
433

434
    if (!data)
J
Jiri Denemark 已提交
435 436
        return NULL;

437
    while (++iterator->pos < data->len) {
438 439
        virCPUx86DataItemPtr item = data->items + iterator->pos;

440
        if (!virCPUx86DataItemMatch(item, &zero))
441
            return item;
442
    }
J
Jiri Denemark 已提交
443

444
    return NULL;
J
Jiri Denemark 已提交
445 446 447
}


448
static virCPUx86DataItemPtr
J
Jiri Denemark 已提交
449 450
virCPUx86DataGet(const virCPUx86Data *data,
                 const virCPUx86DataItem *item)
J
Jiri Denemark 已提交
451
{
452
    size_t i;
J
Jiri Denemark 已提交
453

454
    for (i = 0; i < data->len; i++) {
455 456 457
        virCPUx86DataItemPtr di = data->items + i;
        if (virCPUx86DataItemCmp(di, item) == 0)
            return di;
J
Jiri Denemark 已提交
458 459
    }

460
    return NULL;
J
Jiri Denemark 已提交
461 462
}

463
static void
464
virCPUx86DataClear(virCPUx86Data *data)
J
Jiri Denemark 已提交
465
{
466
    if (!data)
J
Jiri Denemark 已提交
467 468
        return;

469
    VIR_FREE(data->items);
J
Jiri Denemark 已提交
470 471 472
}


473
static void
J
Jiri Denemark 已提交
474
virCPUx86DataFree(virCPUDataPtr data)
475 476 477 478
{
    if (!data)
        return;

479
    virCPUx86DataClear(&data->data.x86);
480 481 482 483
    VIR_FREE(data);
}


484 485
static int
x86DataCopy(virCPUx86Data *dst, const virCPUx86Data *src)
J
Jiri Denemark 已提交
486
{
487
    size_t i;
J
Jiri Denemark 已提交
488

489
    if (VIR_ALLOC_N(dst->items, src->len) < 0)
490
        return -1;
J
Jiri Denemark 已提交
491

492 493
    dst->len = src->len;
    for (i = 0; i < src->len; i++)
494
        dst->items[i] = src->items[i];
J
Jiri Denemark 已提交
495

496
    return 0;
J
Jiri Denemark 已提交
497 498 499
}


500
static int
501 502
virCPUx86DataAddItem(virCPUx86Data *data,
                     const virCPUx86DataItem *item)
J
Jiri Denemark 已提交
503
{
504
    virCPUx86DataItemPtr existing;
J
Jiri Denemark 已提交
505

J
Jiri Denemark 已提交
506
    if ((existing = virCPUx86DataGet(data, item))) {
507
        virCPUx86DataItemSetBits(existing, item);
508
    } else {
509
        if (VIR_APPEND_ELEMENT_COPY(data->items, data->len,
510
                                    *((virCPUx86DataItemPtr)item)) < 0)
511
            return -1;
J
Jiri Denemark 已提交
512

513
        qsort(data->items, data->len,
514
              sizeof(virCPUx86DataItem), virCPUx86DataSorter);
515
    }
J
Jiri Denemark 已提交
516

J
Jiri Denemark 已提交
517 518 519 520 521
    return 0;
}


static int
522 523
x86DataAdd(virCPUx86Data *data1,
           const virCPUx86Data *data2)
J
Jiri Denemark 已提交
524
{
525
    virCPUx86DataIterator iter;
J
Jiri Denemark 已提交
526 527
    virCPUx86DataItemPtr item;

528
    virCPUx86DataIteratorInit(&iter, data2);
J
Jiri Denemark 已提交
529 530 531
    while ((item = virCPUx86DataNext(&iter))) {
        if (virCPUx86DataAddItem(data1, item) < 0)
            return -1;
J
Jiri Denemark 已提交
532
    }
J
Jiri Denemark 已提交
533 534 535 536 537

    return 0;
}


538
static void
539 540
x86DataSubtract(virCPUx86Data *data1,
                const virCPUx86Data *data2)
541
{
542
    virCPUx86DataIterator iter;
543 544
    virCPUx86DataItemPtr item1;
    virCPUx86DataItemPtr item2;
545

546
    virCPUx86DataIteratorInit(&iter, data1);
547
    while ((item1 = virCPUx86DataNext(&iter))) {
548 549
        item2 = virCPUx86DataGet(data2, item1);
        virCPUx86DataItemClearBits(item1, item2);
550 551 552 553
    }
}


J
Jiri Denemark 已提交
554
static void
555 556
x86DataIntersect(virCPUx86Data *data1,
                 const virCPUx86Data *data2)
557
{
558
    virCPUx86DataIterator iter;
559 560
    virCPUx86DataItemPtr item1;
    virCPUx86DataItemPtr item2;
561

562
    virCPUx86DataIteratorInit(&iter, data1);
563
    while ((item1 = virCPUx86DataNext(&iter))) {
J
Jiri Denemark 已提交
564
        item2 = virCPUx86DataGet(data2, item1);
565
        if (item2)
566
            virCPUx86DataItemAndBits(item1, item2);
J
Jiri Denemark 已提交
567
        else
568
            virCPUx86DataItemClearBits(item1, item1);
569 570 571 572
    }
}


J
Jiri Denemark 已提交
573
static bool
574
x86DataIsEmpty(virCPUx86Data *data)
J
Jiri Denemark 已提交
575
{
576
    virCPUx86DataIterator iter;
J
Jiri Denemark 已提交
577

578
    virCPUx86DataIteratorInit(&iter, data);
579
    return !virCPUx86DataNext(&iter);
J
Jiri Denemark 已提交
580
}
J
Jiri Denemark 已提交
581 582


J
Jiri Denemark 已提交
583
static bool
584 585
x86DataIsSubset(const virCPUx86Data *data,
                const virCPUx86Data *subset)
J
Jiri Denemark 已提交
586
{
587
    virCPUx86DataIterator iter;
588 589
    const virCPUx86DataItem *item;
    const virCPUx86DataItem *itemSubset;
J
Jiri Denemark 已提交
590

591
    virCPUx86DataIteratorInit(&iter, subset);
592
    while ((itemSubset = virCPUx86DataNext(&iter))) {
J
Jiri Denemark 已提交
593
        if (!(item = virCPUx86DataGet(data, itemSubset)) ||
594
            !virCPUx86DataItemMatchMasked(item, itemSubset))
J
Jiri Denemark 已提交
595
            return false;
J
Jiri Denemark 已提交
596 597
    }

J
Jiri Denemark 已提交
598
    return true;
J
Jiri Denemark 已提交
599 600 601
}


602 603 604 605
/* also removes all detected features from data */
static int
x86DataToCPUFeatures(virCPUDefPtr cpu,
                     int policy,
606
                     virCPUx86Data *data,
J
Jiri Denemark 已提交
607
                     virCPUx86MapPtr map)
608
{
609
    size_t i;
610

611 612
    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];
613 614
        if (x86DataIsSubset(data, &feature->data)) {
            x86DataSubtract(data, &feature->data);
J
Jiri Denemark 已提交
615 616
            if (virCPUDefAddFeature(cpu, feature->name, policy) < 0)
                return -1;
617 618 619 620 621 622 623
        }
    }

    return 0;
}


J
Jiri Denemark 已提交
624
/* also removes bits corresponding to vendor string from data */
625
static virCPUx86VendorPtr
J
Jiri Denemark 已提交
626
x86DataToVendor(const virCPUx86Data *data,
J
Jiri Denemark 已提交
627
                virCPUx86MapPtr map)
J
Jiri Denemark 已提交
628
{
629
    virCPUx86DataItemPtr item;
630
    size_t i;
J
Jiri Denemark 已提交
631

632 633
    for (i = 0; i < map->nvendors; i++) {
        virCPUx86VendorPtr vendor = map->vendors[i];
J
Jiri Denemark 已提交
634
        if ((item = virCPUx86DataGet(data, &vendor->data)) &&
635
            virCPUx86DataItemMatchMasked(item, &vendor->data)) {
636
            virCPUx86DataItemClearBits(item, &vendor->data);
J
Jiri Denemark 已提交
637 638 639 640 641 642 643 644
            return vendor;
        }
    }

    return NULL;
}


645
static int
646
virCPUx86VendorToData(const char *vendor,
647
                      virCPUx86DataItemPtr item)
648
{
649
    virCPUx86CPUIDPtr cpuid;
650

651 652 653 654 655 656
    if (strlen(vendor) != VENDOR_STRING_LENGTH) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid CPU vendor string '%s'"), vendor);
        return -1;
    }

657 658
    item->type = VIR_CPU_X86_DATA_CPUID;
    cpuid = &item->data.cpuid;
659 660 661 662 663 664 665 666 667 668
    cpuid->eax_in = 0;
    cpuid->ecx_in = 0;
    cpuid->ebx = virReadBufInt32LE(vendor);
    cpuid->edx = virReadBufInt32LE(vendor + 4);
    cpuid->ecx = virReadBufInt32LE(vendor + 8);

    return 0;
}


669 670
static uint32_t
x86MakeSignature(unsigned int family,
671 672
                 unsigned int model,
                 unsigned int stepping)
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
{
    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]
692
     * stepping = eax[3:0]
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
     */

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

712 713
    /* Step */
    sig |= stepping & 0xf;
714 715 716 717 718

    return sig;
}


719 720 721 722 723 724
static void
x86DataToSignatureFull(const virCPUx86Data *data,
                       unsigned int *family,
                       unsigned int *model,
                       unsigned int *stepping)
{
725 726 727
    virCPUx86DataItem leaf1 = CPUID(.eax_in = 0x1);
    virCPUx86DataItemPtr item;
    virCPUx86CPUIDPtr cpuid;
728 729 730

    *family = *model = *stepping = 0;

J
Jiri Denemark 已提交
731
    if (!(item = virCPUx86DataGet(data, &leaf1)))
732 733
        return;

734
    cpuid = &item->data.cpuid;
735 736 737 738 739 740
    *family = ((cpuid->eax >> 20) & 0xff) + ((cpuid->eax >> 8) & 0xf);
    *model = ((cpuid->eax >> 12) & 0xf0) + ((cpuid->eax >> 4) & 0xf);
    *stepping = cpuid->eax & 0xf;
}


741 742 743 744 745 746
/* Mask out irrelevant bits (R and Step) from processor signature. */
#define SIGNATURE_MASK  0x0fff3ff0

static uint32_t
x86DataToSignature(const virCPUx86Data *data)
{
747
    virCPUx86DataItem leaf1 = CPUID(.eax_in = 0x1);
748
    virCPUx86DataItemPtr item;
749

J
Jiri Denemark 已提交
750
    if (!(item = virCPUx86DataGet(data, &leaf1)))
751 752
        return 0;

753
    return item->data.cpuid.eax & SIGNATURE_MASK;
754 755 756 757 758 759 760
}


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

763
    return virCPUx86DataAddItem(data, &leaf1);
764 765 766
}


767
static virCPUDefPtr
768
x86DataToCPU(const virCPUx86Data *data,
J
Jiri Denemark 已提交
769
             virCPUx86ModelPtr model,
770 771
             virCPUx86MapPtr map,
             virDomainCapsCPUModelPtr hvModel)
772 773
{
    virCPUDefPtr cpu;
774 775
    virCPUx86Data copy = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data modelData = VIR_CPU_X86_DATA_INIT;
776
    virCPUx86VendorPtr vendor;
777

778
    cpu = virCPUDefNew();
779

780 781 782 783
    cpu->model = g_strdup(model->name);

    if (x86DataCopy(&copy, data) < 0 ||
        x86DataCopy(&modelData, &model->data) < 0)
784
        goto error;
J
Jiri Denemark 已提交
785

786 787 788
    if ((vendor = x86DataToVendor(&copy, map)))
        cpu->vendor = g_strdup(vendor->name);

789 790
    x86DataSubtract(&copy, &modelData);
    x86DataSubtract(&modelData, data);
791

792 793 794 795 796 797 798 799 800 801 802
    /* 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))
803 804
                if (x86DataAdd(&modelData, &feature->data) < 0)
                    goto error;
805 806 807
        }
    }

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

811 812
    if (x86DataToCPUFeatures(cpu, VIR_CPU_FEATURE_REQUIRE, &copy, map) ||
        x86DataToCPUFeatures(cpu, VIR_CPU_FEATURE_DISABLE, &modelData, map))
813
        goto error;
814

815
 cleanup:
816 817
    virCPUx86DataClear(&modelData);
    virCPUx86DataClear(&copy);
818 819
    return cpu;

820
 error:
821 822 823 824 825 826
    virCPUDefFree(cpu);
    cpu = NULL;
    goto cleanup;
}


J
Jiri Denemark 已提交
827
static void
828
x86VendorFree(virCPUx86VendorPtr vendor)
J
Jiri Denemark 已提交
829 830 831 832 833 834
{
    if (!vendor)
        return;

    VIR_FREE(vendor->name);
    VIR_FREE(vendor);
J
Jiri Denemark 已提交
835
}
J
Jiri Denemark 已提交
836 837


838
static virCPUx86VendorPtr
J
Jiri Denemark 已提交
839
x86VendorFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
840 841
              const char *name)
{
842
    size_t i;
J
Jiri Denemark 已提交
843

844 845 846
    for (i = 0; i < map->nvendors; i++) {
        if (STREQ(map->vendors[i]->name, name))
            return map->vendors[i];
J
Jiri Denemark 已提交
847 848 849 850 851 852
    }

    return NULL;
}


853
static int
J
Jiri Denemark 已提交
854
x86VendorParse(xmlXPathContextPtr ctxt,
855 856
               const char *name,
               void *data)
J
Jiri Denemark 已提交
857
{
858
    virCPUx86MapPtr map = data;
859
    virCPUx86VendorPtr vendor = NULL;
J
Jiri Denemark 已提交
860
    char *string = NULL;
861
    int ret = -1;
J
Jiri Denemark 已提交
862 863

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

866
    vendor->name = g_strdup(name);
J
Jiri Denemark 已提交
867 868

    if (x86VendorFind(map, vendor->name)) {
869 870
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU vendor %s already defined"), vendor->name);
871
        goto cleanup;
J
Jiri Denemark 已提交
872 873 874 875
    }

    string = virXPathString("string(@string)", ctxt);
    if (!string) {
876
        virReportError(VIR_ERR_INTERNAL_ERROR,
877 878
                       _("Missing vendor string for CPU vendor %s"),
                       vendor->name);
879
        goto cleanup;
J
Jiri Denemark 已提交
880 881
    }

882
    if (virCPUx86VendorToData(string, &vendor->data) < 0)
883
        goto cleanup;
E
Eric Blake 已提交
884

885
    if (VIR_APPEND_ELEMENT(map->vendors, map->nvendors, vendor) < 0)
886
        goto cleanup;
887 888 889

    ret = 0;

J
Jiri Denemark 已提交
890
 cleanup:
891
    x86VendorFree(vendor);
J
Jiri Denemark 已提交
892
    VIR_FREE(string);
893
    return ret;
J
Jiri Denemark 已提交
894 895 896
}


897
static virCPUx86FeaturePtr
J
Jiri Denemark 已提交
898 899
x86FeatureNew(void)
{
900
    virCPUx86FeaturePtr feature;
J
Jiri Denemark 已提交
901 902 903 904 905 906 907 908

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

    return feature;
}


J
Jiri Denemark 已提交
909
static void
910
x86FeatureFree(virCPUx86FeaturePtr feature)
J
Jiri Denemark 已提交
911
{
912
    if (!feature)
J
Jiri Denemark 已提交
913 914 915
        return;

    VIR_FREE(feature->name);
916
    virCPUx86DataClear(&feature->data);
J
Jiri Denemark 已提交
917 918 919 920
    VIR_FREE(feature);
}


J
Jiri Denemark 已提交
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
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;
}


942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
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;
}


958
static char *
J
Jiri Denemark 已提交
959
x86FeatureNames(virCPUx86MapPtr map,
960
                const char *separator,
961
                virCPUx86Data *data)
962 963 964
{
    virBuffer ret = VIR_BUFFER_INITIALIZER;
    bool first = true;
965
    size_t i;
966 967 968

    virBufferAdd(&ret, "", 0);

969 970
    for (i = 0; i < map->nfeatures; i++) {
        virCPUx86FeaturePtr feature = map->features[i];
971
        if (x86DataIsSubset(data, &feature->data)) {
972 973 974 975 976
            if (!first)
                virBufferAdd(&ret, separator, -1);
            else
                first = false;

977
            virBufferAdd(&ret, feature->name, -1);
978 979 980 981 982 983 984
        }
    }

    return virBufferContentAndReset(&ret);
}


985 986
static int
x86ParseCPUID(xmlXPathContextPtr ctxt,
987
              virCPUx86DataItemPtr item)
988
{
989
    virCPUx86CPUIDPtr cpuid;
990
    unsigned long eax_in, ecx_in;
991
    unsigned long eax, ebx, ecx, edx;
992
    int ret_eax_in, ret_ecx_in, ret_eax, ret_ebx, ret_ecx, ret_edx;
993

994
    memset(item, 0, sizeof(*item));
995

996
    eax_in = ecx_in = 0;
997 998
    eax = ebx = ecx = edx = 0;
    ret_eax_in = virXPathULongHex("string(@eax_in)", ctxt, &eax_in);
999
    ret_ecx_in = virXPathULongHex("string(@ecx_in)", ctxt, &ecx_in);
1000 1001 1002 1003 1004
    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);

1005
    if (ret_eax_in < 0 || ret_ecx_in == -2 ||
1006
        ret_eax == -2 || ret_ebx == -2 || ret_ecx == -2 || ret_edx == -2)
1007 1008
        return -1;

1009 1010
    item->type = VIR_CPU_X86_DATA_CPUID;
    cpuid = &item->data.cpuid;
1011
    cpuid->eax_in = eax_in;
1012
    cpuid->ecx_in = ecx_in;
1013 1014 1015 1016 1017 1018 1019 1020
    cpuid->eax = eax;
    cpuid->ebx = ebx;
    cpuid->ecx = ecx;
    cpuid->edx = edx;
    return 0;
}


1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
static int
x86ParseMSR(xmlXPathContextPtr ctxt,
            virCPUx86DataItemPtr item)
{
    virCPUx86MSRPtr msr;
    unsigned long index;
    unsigned long eax;
    unsigned long edx;

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

    if (virXPathULongHex("string(@index)", ctxt, &index) < 0 ||
        virXPathULongHex("string(@eax)", ctxt, &eax) < 0 ||
        virXPathULongHex("string(@edx)", ctxt, &edx) < 0)
        return -1;

    item->type = VIR_CPU_X86_DATA_MSR;
    msr = &item->data.msr;
    msr->index = index;
    msr->eax = eax;
    msr->edx = edx;
    return 0;
}


1046
static int
J
Jiri Denemark 已提交
1047
x86FeatureParse(xmlXPathContextPtr ctxt,
1048 1049
                const char *name,
                void *data)
J
Jiri Denemark 已提交
1050
{
1051
    virCPUx86MapPtr map = data;
J
Jiri Denemark 已提交
1052
    xmlNodePtr *nodes = NULL;
1053
    virCPUx86FeaturePtr feature;
1054
    virCPUx86DataItem item;
1055
    size_t i;
J
Jiri Denemark 已提交
1056
    int n;
1057
    char *str = NULL;
1058
    int ret = -1;
J
Jiri Denemark 已提交
1059

J
Jiri Denemark 已提交
1060
    if (!(feature = x86FeatureNew()))
1061
        goto cleanup;
J
Jiri Denemark 已提交
1062

J
Jiri Denemark 已提交
1063
    feature->migratable = true;
1064

1065
    feature->name = g_strdup(name);
J
Jiri Denemark 已提交
1066 1067

    if (x86FeatureFind(map, feature->name)) {
1068 1069
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU feature %s already defined"), feature->name);
1070
        goto cleanup;
J
Jiri Denemark 已提交
1071 1072
    }

1073 1074
    str = virXPathString("string(@migratable)", ctxt);
    if (STREQ_NULLABLE(str, "no"))
J
Jiri Denemark 已提交
1075
        feature->migratable = false;
1076

1077
    n = virXPathNodeSet("./cpuid|./msr", ctxt, &nodes);
J
Jiri Denemark 已提交
1078
    if (n < 0)
1079
        goto cleanup;
J
Jiri Denemark 已提交
1080

1081 1082
    if (n == 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
1083
                       _("Missing cpuid or msr element in feature %s"),
1084 1085 1086 1087
                       feature->name);
        goto cleanup;
    }

J
Jiri Denemark 已提交
1088 1089
    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
        if (virXMLNodeNameEqual(nodes[i], "cpuid")) {
            if (x86ParseCPUID(ctxt, &item) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid cpuid[%zu] in %s feature"),
                               i, feature->name);
                goto cleanup;
            }
        } else {
            if (x86ParseMSR(ctxt, &item) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid msr[%zu] in %s feature"),
                               i, feature->name);
                goto cleanup;
            }
J
Jiri Denemark 已提交
1104
        }
1105

1106
        if (virCPUx86DataAddItem(&feature->data, &item))
1107
            goto cleanup;
J
Jiri Denemark 已提交
1108 1109
    }

1110 1111 1112 1113
    if (!feature->migratable &&
        VIR_APPEND_ELEMENT_COPY(map->migrate_blockers,
                                map->nblockers,
                                feature) < 0)
1114
        goto cleanup;
1115 1116

    if (VIR_APPEND_ELEMENT(map->features, map->nfeatures, feature) < 0)
1117
        goto cleanup;
1118 1119 1120

    ret = 0;

J
Jiri Denemark 已提交
1121
 cleanup:
1122
    x86FeatureFree(feature);
1123
    VIR_FREE(nodes);
1124
    VIR_FREE(str);
1125
    return ret;
J
Jiri Denemark 已提交
1126 1127 1128
}


J
Jiri Denemark 已提交
1129
static virCPUx86ModelPtr
J
Jiri Denemark 已提交
1130 1131
x86ModelNew(void)
{
J
Jiri Denemark 已提交
1132
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
1133 1134 1135 1136 1137 1138 1139 1140

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

    return model;
}


J
Jiri Denemark 已提交
1141
static void
J
Jiri Denemark 已提交
1142
x86ModelFree(virCPUx86ModelPtr model)
J
Jiri Denemark 已提交
1143
{
1144
    if (!model)
J
Jiri Denemark 已提交
1145 1146 1147
        return;

    VIR_FREE(model->name);
1148
    VIR_FREE(model->signatures);
1149
    virCPUx86DataClear(&model->data);
J
Jiri Denemark 已提交
1150 1151 1152 1153
    VIR_FREE(model);
}


1154 1155 1156 1157
static int
x86ModelCopySignatures(virCPUx86ModelPtr dst,
                       virCPUx86ModelPtr src)
{
1158 1159
    size_t i;

1160 1161 1162
    if (src->nsignatures == 0)
        return 0;

1163 1164 1165 1166 1167 1168
    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];
1169 1170 1171 1172 1173

    return 0;
}


J
Jiri Denemark 已提交
1174 1175
static virCPUx86ModelPtr
x86ModelCopy(virCPUx86ModelPtr model)
J
Jiri Denemark 已提交
1176
{
J
Jiri Denemark 已提交
1177
    virCPUx86ModelPtr copy;
J
Jiri Denemark 已提交
1178

1179 1180 1181 1182 1183 1184
    if (VIR_ALLOC(copy) < 0)
        return NULL;

    copy->name = g_strdup(model->name);

    if (x86ModelCopySignatures(copy, model) < 0 ||
1185
        x86DataCopy(&copy->data, &model->data) < 0) {
J
Jiri Denemark 已提交
1186 1187 1188 1189
        x86ModelFree(copy);
        return NULL;
    }

J
Jiri Denemark 已提交
1190
    copy->vendor = model->vendor;
J
Jiri Denemark 已提交
1191 1192 1193 1194 1195

    return copy;
}


J
Jiri Denemark 已提交
1196
static virCPUx86ModelPtr
J
Jiri Denemark 已提交
1197
x86ModelFind(virCPUx86MapPtr map,
J
Jiri Denemark 已提交
1198 1199
             const char *name)
{
1200
    size_t i;
J
Jiri Denemark 已提交
1201

1202 1203 1204
    for (i = 0; i < map->nmodels; i++) {
        if (STREQ(map->models[i]->name, name))
            return map->models[i];
J
Jiri Denemark 已提交
1205 1206 1207 1208 1209 1210
    }

    return NULL;
}


1211 1212 1213 1214 1215 1216 1217 1218 1219
/*
 * 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 已提交
1220
static virCPUx86ModelPtr
1221
x86ModelFromCPU(const virCPUDef *cpu,
J
Jiri Denemark 已提交
1222
                virCPUx86MapPtr map,
J
Jiri Denemark 已提交
1223 1224
                int policy)
{
J
Jiri Denemark 已提交
1225
    virCPUx86ModelPtr model = NULL;
1226
    size_t i;
J
Jiri Denemark 已提交
1227

1228 1229 1230 1231
    /* host CPU only contains required features; requesting other features
     * just returns an empty model
     */
    if (cpu->type == VIR_CPU_TYPE_HOST &&
1232 1233
        policy != VIR_CPU_FEATURE_REQUIRE &&
        policy != -1)
1234 1235
        return x86ModelNew();

J
Jiri Denemark 已提交
1236 1237
    if (cpu->model &&
        (policy == VIR_CPU_FEATURE_REQUIRE || policy == -1)) {
1238
        if (!(model = x86ModelFind(map, cpu->model))) {
1239 1240
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU model %s"), cpu->model);
1241
            return NULL;
J
Jiri Denemark 已提交
1242 1243
        }

1244 1245 1246
        model = x86ModelCopy(model);
    } else {
        model = x86ModelNew();
J
Jiri Denemark 已提交
1247
    }
J
Jiri Denemark 已提交
1248

1249 1250 1251
    if (!model)
        return NULL;

J
Jiri Denemark 已提交
1252
    for (i = 0; i < cpu->nfeatures; i++) {
1253
        virCPUx86FeaturePtr feature;
1254
        virCPUFeaturePolicy fpol;
J
Jiri Denemark 已提交
1255

1256 1257 1258 1259 1260 1261 1262
        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 已提交
1263 1264
            continue;

1265
        if (!(feature = x86FeatureFind(map, cpu->features[i].name))) {
1266 1267
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown CPU feature %s"), cpu->features[i].name);
J
Jiri Denemark 已提交
1268 1269 1270
            goto error;
        }

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        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) {
1290
            goto error;
1291
        }
J
Jiri Denemark 已提交
1292 1293 1294 1295
    }

    return model;

1296
 error:
J
Jiri Denemark 已提交
1297 1298 1299 1300 1301
    x86ModelFree(model);
    return NULL;
}


1302
static virCPUx86CompareResult
J
Jiri Denemark 已提交
1303 1304
x86ModelCompare(virCPUx86ModelPtr model1,
                virCPUx86ModelPtr model2)
J
Jiri Denemark 已提交
1305
{
1306
    virCPUx86CompareResult result = EQUAL;
1307 1308
    virCPUx86DataIterator iter1;
    virCPUx86DataIterator iter2;
1309 1310
    virCPUx86DataItemPtr item1;
    virCPUx86DataItemPtr item2;
J
Jiri Denemark 已提交
1311

1312 1313
    virCPUx86DataIteratorInit(&iter1, &model1->data);
    virCPUx86DataIteratorInit(&iter2, &model2->data);
1314
    while ((item1 = virCPUx86DataNext(&iter1))) {
1315
        virCPUx86CompareResult match = SUPERSET;
J
Jiri Denemark 已提交
1316

J
Jiri Denemark 已提交
1317
        if ((item2 = virCPUx86DataGet(&model2->data, item1))) {
1318
            if (virCPUx86DataItemMatch(item1, item2))
J
Jiri Denemark 已提交
1319
                continue;
1320
            else if (!virCPUx86DataItemMatchMasked(item1, item2))
J
Jiri Denemark 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329
                match = SUBSET;
        }

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

1330
    while ((item2 = virCPUx86DataNext(&iter2))) {
1331
        virCPUx86CompareResult match = SUBSET;
J
Jiri Denemark 已提交
1332

J
Jiri Denemark 已提交
1333
        if ((item1 = virCPUx86DataGet(&model1->data, item2))) {
1334
            if (virCPUx86DataItemMatch(item2, item1))
J
Jiri Denemark 已提交
1335
                continue;
1336
            else if (!virCPUx86DataItemMatchMasked(item2, item1))
J
Jiri Denemark 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                match = SUPERSET;
        }

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

    return result;
}


1350 1351 1352 1353 1354
static int
x86ModelParseAncestor(virCPUx86ModelPtr model,
                      xmlXPathContextPtr ctxt,
                      virCPUx86MapPtr map)
{
1355
    g_autofree char *name = NULL;
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    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;
1378 1379
    if (x86ModelCopySignatures(model, ancestor) < 0 ||
        x86DataCopy(&model->data, &ancestor->data) < 0)
1380 1381 1382 1383 1384 1385
        return -1;

    return 0;
}


1386
static int
1387 1388
x86ModelParseSignatures(virCPUx86ModelPtr model,
                        xmlXPathContextPtr ctxt)
J
Jiri Denemark 已提交
1389
{
1390
    g_autofree xmlNodePtr *nodes = NULL;
1391 1392 1393 1394 1395 1396 1397
    xmlNodePtr root = ctxt->node;
    size_t i;
    int n;

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

1398 1399
    /* Remove inherited signatures. */
    VIR_FREE(model->signatures);
J
Jiri Denemark 已提交
1400

1401 1402 1403 1404 1405
    model->nsignatures = n;
    if (VIR_ALLOC_N(model->signatures, n) < 0)
       return -1;

    for (i = 0; i < n; i++) {
1406 1407 1408 1409
        unsigned int sigFamily = 0;
        unsigned int sigModel = 0;
        int rc;

1410
        ctxt->node = nodes[i];
1411

1412
        rc = virXPathUInt("string(@family)", ctxt, &sigFamily);
1413 1414 1415 1416
        if (rc < 0 || sigFamily == 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid CPU signature family in model %s"),
                           model->name);
1417
            return -1;
1418 1419
        }

1420
        rc = virXPathUInt("string(@model)", ctxt, &sigModel);
1421
        if (rc < 0) {
1422 1423 1424
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid CPU signature model in model %s"),
                           model->name);
1425
            return -1;
1426 1427
        }

1428
        model->signatures[i] = x86MakeSignature(sigFamily, sigModel, 0);
1429 1430
    }

1431
    ctxt->node = root;
1432 1433 1434 1435
    return 0;
}


1436 1437 1438 1439 1440
static int
x86ModelParseVendor(virCPUx86ModelPtr model,
                    xmlXPathContextPtr ctxt,
                    virCPUx86MapPtr map)
{
1441
    g_autofree char *vendor = NULL;
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
    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;
}


1466 1467 1468 1469 1470
static int
x86ModelParseFeatures(virCPUx86ModelPtr model,
                      xmlXPathContextPtr ctxt,
                      virCPUx86MapPtr map)
{
1471
    g_autofree xmlNodePtr *nodes = NULL;
1472 1473 1474 1475 1476 1477 1478
    size_t i;
    int n;

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

    for (i = 0; i < n; i++) {
1479
        g_autofree char *ftname = NULL;
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
        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;
}


1504 1505 1506 1507 1508 1509
static int
x86ModelParse(xmlXPathContextPtr ctxt,
              const char *name,
              void *data)
{
    virCPUx86MapPtr map = data;
1510
    virCPUx86ModelPtr model = NULL;
1511 1512
    int ret = -1;

1513 1514 1515 1516 1517 1518
    if (x86ModelFind(map, name)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Multiple definitions of CPU model '%s'"), name);
        goto cleanup;
    }

1519 1520 1521
    if (!(model = x86ModelNew()))
        goto cleanup;

1522
    model->name = g_strdup(name);
1523 1524 1525 1526

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

1527
    if (x86ModelParseSignatures(model, ctxt) < 0)
1528 1529
        goto cleanup;

1530 1531
    if (x86ModelParseVendor(model, ctxt, map) < 0)
        goto cleanup;
J
Jiri Denemark 已提交
1532

1533
    if (x86ModelParseFeatures(model, ctxt, map) < 0)
1534
        goto cleanup;
J
Jiri Denemark 已提交
1535

1536
    if (VIR_APPEND_ELEMENT(map->models, map->nmodels, model) < 0)
1537
        goto cleanup;
1538 1539 1540

    ret = 0;

J
Jiri Denemark 已提交
1541
 cleanup:
1542
    x86ModelFree(model);
1543
    return ret;
J
Jiri Denemark 已提交
1544 1545 1546
}


J
Jiri Denemark 已提交
1547
static void
J
Jiri Denemark 已提交
1548
x86MapFree(virCPUx86MapPtr map)
J
Jiri Denemark 已提交
1549
{
1550 1551
    size_t i;

1552
    if (!map)
J
Jiri Denemark 已提交
1553 1554
        return;

1555 1556 1557
    for (i = 0; i < map->nfeatures; i++)
        x86FeatureFree(map->features[i]);
    VIR_FREE(map->features);
J
Jiri Denemark 已提交
1558

1559 1560 1561
    for (i = 0; i < map->nmodels; i++)
        x86ModelFree(map->models[i]);
    VIR_FREE(map->models);
J
Jiri Denemark 已提交
1562

1563 1564 1565
    for (i = 0; i < map->nvendors; i++)
        x86VendorFree(map->vendors[i]);
    VIR_FREE(map->vendors);
1566

1567 1568 1569 1570
    /* migrate_blockers only points to the features from map->features list,
     * which were already freed above
     */
    VIR_FREE(map->migrate_blockers);
1571

J
Jiri Denemark 已提交
1572 1573 1574 1575
    VIR_FREE(map);
}


J
Jiri Denemark 已提交
1576
static virCPUx86MapPtr
1577
virCPUx86LoadMap(void)
J
Jiri Denemark 已提交
1578
{
J
Jiri Denemark 已提交
1579
    virCPUx86MapPtr map;
J
Jiri Denemark 已提交
1580

1581
    if (VIR_ALLOC(map) < 0)
J
Jiri Denemark 已提交
1582 1583
        return NULL;

1584
    if (cpuMapLoad("x86", x86VendorParse, x86FeatureParse, x86ModelParse, map) < 0)
J
Jiri Denemark 已提交
1585 1586 1587 1588
        goto error;

    return map;

1589
 error:
J
Jiri Denemark 已提交
1590 1591 1592 1593 1594
    x86MapFree(map);
    return NULL;
}


1595
int
1596
virCPUx86DriverOnceInit(void)
1597
{
J
Jiri Denemark 已提交
1598
    if (!(cpuMap = virCPUx86LoadMap()))
1599 1600 1601 1602 1603 1604
        return -1;

    return 0;
}


J
Jiri Denemark 已提交
1605
static virCPUx86MapPtr
1606 1607
virCPUx86GetMap(void)
{
1608
    if (virCPUx86DriverInitialize() < 0)
1609 1610
        return NULL;

J
Jiri Denemark 已提交
1611
    return cpuMap;
1612 1613 1614
}


1615
static char *
J
Jiri Denemark 已提交
1616
virCPUx86DataFormat(const virCPUData *data)
1617
{
1618
    virCPUx86DataIterator iter;
1619
    virCPUx86DataItemPtr item;
1620 1621
    virBuffer buf = VIR_BUFFER_INITIALIZER;

1622 1623
    virCPUx86DataIteratorInit(&iter, &data->data.x86);

1624
    virBufferAddLit(&buf, "<cpudata arch='x86'>\n");
1625
    while ((item = virCPUx86DataNext(&iter))) {
1626
        virCPUx86CPUIDPtr cpuid;
1627
        virCPUx86MSRPtr msr;
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639

        switch (item->type) {
        case VIR_CPU_X86_DATA_CPUID:
            cpuid = &item->data.cpuid;
            virBufferAsprintf(&buf,
                              "  <cpuid eax_in='0x%08x' ecx_in='0x%08x'"
                              " eax='0x%08x' ebx='0x%08x'"
                              " ecx='0x%08x' edx='0x%08x'/>\n",
                              cpuid->eax_in, cpuid->ecx_in,
                              cpuid->eax, cpuid->ebx, cpuid->ecx, cpuid->edx);
            break;

1640 1641 1642 1643 1644 1645 1646
        case VIR_CPU_X86_DATA_MSR:
            msr = &item->data.msr;
            virBufferAsprintf(&buf,
                              "  <msr index='0x%x' eax='0x%08x' edx='0x%08x'/>\n",
                              msr->index, msr->eax, msr->edx);
            break;

1647 1648 1649 1650
        case VIR_CPU_X86_DATA_NONE:
        default:
            break;
        }
1651 1652 1653 1654 1655 1656 1657 1658
    }
    virBufferAddLit(&buf, "</cpudata>\n");

    return virBufferContentAndReset(&buf);
}


static virCPUDataPtr
J
Jiri Denemark 已提交
1659
virCPUx86DataParse(xmlXPathContextPtr ctxt)
1660 1661 1662
{
    xmlNodePtr *nodes = NULL;
    virCPUDataPtr cpuData = NULL;
1663
    virCPUx86DataItem item;
1664 1665 1666
    size_t i;
    int n;

1667
    n = virXPathNodeSet("/cpudata/cpuid|/cpudata/msr", ctxt, &nodes);
J
Jiri Denemark 已提交
1668
    if (n <= 0) {
1669 1670
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no x86 CPU data found"));
1671
        goto error;
1672 1673
    }

1674 1675 1676
    if (!(cpuData = virCPUDataNew(VIR_ARCH_X86_64)))
        goto error;

1677 1678
    for (i = 0; i < n; i++) {
        ctxt->node = nodes[i];
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
        if (virXMLNodeNameEqual(nodes[i], "cpuid")) {
            if (x86ParseCPUID(ctxt, &item) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("failed to parse cpuid[%zu]"), i);
                goto error;
            }
        } else {
            if (x86ParseMSR(ctxt, &item) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("failed to parse msr[%zu]"), i);
                goto error;
            }
1691
        }
1692

1693
        if (virCPUx86DataAdd(cpuData, &item) < 0)
1694
            goto error;
1695 1696
    }

1697
 cleanup:
1698 1699
    VIR_FREE(nodes);
    return cpuData;
1700 1701

 error:
J
Jiri Denemark 已提交
1702
    virCPUx86DataFree(cpuData);
1703 1704
    cpuData = NULL;
    goto cleanup;
1705 1706 1707
}


1708 1709 1710
/* A helper macro to exit the cpu computation function without writing
 * redundant code:
 * MSG: error message
1711
 * CPU_DEF: a virCPUx86Data pointer with flags that are conflicting
1712 1713 1714 1715
 * RET: return code to set
 *
 * This macro generates the error string outputs it into logs.
 */
1716 1717 1718 1719 1720 1721 1722
#define virX86CpuIncompatible(MSG, CPU_DEF) \
        do { \
            char *flagsStr = NULL; \
            if (!(flagsStr = x86FeatureNames(map, ", ", (CPU_DEF)))) { \
                virReportOOMError(); \
                goto error; \
            } \
1723 1724
            if (message) \
                *message = g_strdup_printf("%s: %s", _(MSG), flagsStr); \
1725 1726 1727
            VIR_DEBUG("%s: %s", MSG, flagsStr); \
            VIR_FREE(flagsStr); \
            ret = VIR_CPU_COMPARE_INCOMPATIBLE; \
1728 1729
        } while (0)

1730

J
Jiri Denemark 已提交
1731 1732 1733
static virCPUCompareResult
x86Compute(virCPUDefPtr host,
           virCPUDefPtr cpu,
1734
           virCPUDataPtr *guest,
1735
           char **message)
J
Jiri Denemark 已提交
1736
{
J
Jiri Denemark 已提交
1737
    virCPUx86MapPtr map = NULL;
J
Jiri Denemark 已提交
1738 1739 1740 1741 1742 1743 1744 1745
    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;
1746
    virCPUDataPtr guestData = NULL;
J
Jiri Denemark 已提交
1747
    virCPUCompareResult ret;
1748
    virCPUx86CompareResult result;
J
Jiri Denemark 已提交
1749
    virArch arch;
1750
    size_t i;
J
Jiri Denemark 已提交
1751

1752
    if (cpu->arch != VIR_ARCH_NONE) {
J
Jiri Denemark 已提交
1753 1754
        bool found = false;

1755
        for (i = 0; i < G_N_ELEMENTS(archs); i++) {
1756
            if (archs[i] == cpu->arch) {
J
Jiri Denemark 已提交
1757 1758 1759 1760 1761
                found = true;
                break;
            }
        }

1762
        if (!found) {
1763 1764
            VIR_DEBUG("CPU arch %s does not match host arch",
                      virArchToString(cpu->arch));
1765 1766 1767 1768
            if (message) {
                *message = g_strdup_printf(_("CPU arch %s does not match host arch"),
                                           virArchToString(cpu->arch));
            }
J
Jiri Denemark 已提交
1769
            return VIR_CPU_COMPARE_INCOMPATIBLE;
1770
        }
J
Jiri Denemark 已提交
1771 1772 1773
        arch = cpu->arch;
    } else {
        arch = host->arch;
J
Jiri Denemark 已提交
1774 1775
    }

J
Jiri Denemark 已提交
1776 1777 1778 1779
    if (cpu->vendor &&
        (!host->vendor || STRNEQ(cpu->vendor, host->vendor))) {
        VIR_DEBUG("host CPU vendor does not match required CPU vendor %s",
                  cpu->vendor);
1780 1781 1782 1783 1784
        if (message) {
            *message = g_strdup_printf(_("host CPU vendor does not match required "
                                         "CPU vendor %s"),
                                       cpu->vendor);
        }
1785

J
Jiri Denemark 已提交
1786 1787 1788
        return VIR_CPU_COMPARE_INCOMPATIBLE;
    }

1789
    if (!(map = virCPUx86GetMap()) ||
J
Jiri Denemark 已提交
1790
        !(host_model = x86ModelFromCPU(host, map, -1)) ||
J
Jiri Denemark 已提交
1791 1792 1793 1794 1795
        !(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 已提交
1796 1797
        goto error;

1798 1799
    x86DataIntersect(&cpu_forbid->data, &host_model->data);
    if (!x86DataIsEmpty(&cpu_forbid->data)) {
1800
        virX86CpuIncompatible(N_("Host CPU provides forbidden features"),
1801
                              &cpu_forbid->data);
1802
        goto cleanup;
J
Jiri Denemark 已提交
1803 1804
    }

1805 1806 1807
    /* first remove features that were inherited from the CPU model and were
     * explicitly forced, disabled, or made optional
     */
1808 1809 1810
    x86DataSubtract(&cpu_require->data, &cpu_force->data);
    x86DataSubtract(&cpu_require->data, &cpu_optional->data);
    x86DataSubtract(&cpu_require->data, &cpu_disable->data);
J
Jiri Denemark 已提交
1811 1812
    result = x86ModelCompare(host_model, cpu_require);
    if (result == SUBSET || result == UNRELATED) {
1813
        x86DataSubtract(&cpu_require->data, &host_model->data);
1814 1815
        virX86CpuIncompatible(N_("Host CPU does not provide required "
                                 "features"),
1816
                              &cpu_require->data);
1817
        goto cleanup;
J
Jiri Denemark 已提交
1818 1819 1820 1821
    }

    ret = VIR_CPU_COMPARE_IDENTICAL;

1822
    if (!(diff = x86ModelCopy(host_model)))
1823
        goto error;
J
Jiri Denemark 已提交
1824

1825 1826 1827 1828
    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 已提交
1829

1830
    if (!x86DataIsEmpty(&diff->data))
J
Jiri Denemark 已提交
1831
        ret = VIR_CPU_COMPARE_SUPERSET;
J
Jiri Denemark 已提交
1832 1833 1834 1835

    if (ret == VIR_CPU_COMPARE_SUPERSET
        && cpu->type == VIR_CPU_TYPE_GUEST
        && cpu->match == VIR_CPU_MATCH_STRICT) {
1836 1837
        virX86CpuIncompatible(N_("Host CPU does not strictly match guest CPU: "
                                 "Extra features"),
1838
                              &diff->data);
1839
        goto cleanup;
J
Jiri Denemark 已提交
1840 1841
    }

1842 1843
    if (guest) {
        if (!(guest_model = x86ModelCopy(host_model)))
1844
            goto error;
J
Jiri Denemark 已提交
1845

1846
        if (cpu->vendor && host_model->vendor &&
1847 1848
            virCPUx86DataAddItem(&guest_model->data,
                                 &host_model->vendor->data) < 0)
1849 1850
            goto error;

1851 1852
        if (host_model->signatures &&
            x86DataAddSignature(&guest_model->data, *host_model->signatures) < 0)
1853 1854
            goto error;

J
Jiri Denemark 已提交
1855 1856
        if (cpu->type == VIR_CPU_TYPE_GUEST
            && cpu->match == VIR_CPU_MATCH_EXACT)
1857
            x86DataSubtract(&guest_model->data, &diff->data);
J
Jiri Denemark 已提交
1858

1859
        if (x86DataAdd(&guest_model->data, &cpu_force->data))
1860
            goto error;
J
Jiri Denemark 已提交
1861

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

1864 1865
        if (!(guestData = virCPUDataNew(arch)) ||
            x86DataCopy(&guestData->data.x86, &guest_model->data) < 0)
1866
            goto error;
1867 1868

        *guest = guestData;
J
Jiri Denemark 已提交
1869 1870
    }

1871
 cleanup:
J
Jiri Denemark 已提交
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
    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;

1883
 error:
J
Jiri Denemark 已提交
1884
    virCPUx86DataFree(guestData);
J
Jiri Denemark 已提交
1885
    ret = VIR_CPU_COMPARE_ERROR;
1886
    goto cleanup;
J
Jiri Denemark 已提交
1887
}
1888
#undef virX86CpuIncompatible
J
Jiri Denemark 已提交
1889 1890 1891


static virCPUCompareResult
J
Jiri Denemark 已提交
1892 1893 1894
virCPUx86Compare(virCPUDefPtr host,
                 virCPUDefPtr cpu,
                 bool failIncompatible)
J
Jiri Denemark 已提交
1895
{
J
Jiri Denemark 已提交
1896 1897 1898
    virCPUCompareResult ret = VIR_CPU_COMPARE_ERROR;
    virCPUx86MapPtr map;
    virCPUx86ModelPtr model = NULL;
1899 1900
    char *message = NULL;

J
Jiri Denemark 已提交
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    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;
    }

1912 1913
    ret = x86Compute(host, cpu, NULL, &message);

J
Jiri Denemark 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
    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);
                }
            }
1948 1949 1950
        }
    }

J
Jiri Denemark 已提交
1951 1952 1953
 cleanup:
    VIR_FREE(message);
    x86ModelFree(model);
1954
    return ret;
J
Jiri Denemark 已提交
1955 1956 1957
}


1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
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;
}


1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
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]);
    }

J
Ján Tomko 已提交
1984
    virBufferTrim(&buf, ",");
1985 1986 1987 1988 1989

    return virBufferContentAndReset(&buf);
}


1990
/*
1991 1992
 * Checks whether a candidate model is a better fit for the CPU data than the
 * current model.
1993
 *
1994 1995 1996
 * Returns 0 if current is better,
 *         1 if candidate is better,
 *         2 if candidate is the best one (search should stop now).
1997 1998
 */
static int
1999 2000 2001
x86DecodeUseCandidate(virCPUx86ModelPtr current,
                      virCPUDefPtr cpuCurrent,
                      virCPUx86ModelPtr candidate,
2002
                      virCPUDefPtr cpuCandidate,
2003
                      uint32_t signature,
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
                      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;
        }
    }

2016 2017
    if (preferred && STREQ(cpuCandidate->model, preferred)) {
        VIR_DEBUG("%s is the preferred model", cpuCandidate->model);
2018
        return 2;
2019
    }
2020

2021 2022
    if (!cpuCurrent) {
        VIR_DEBUG("%s is better than nothing", cpuCandidate->model);
2023
        return 1;
2024
    }
2025

2026 2027 2028 2029 2030
    /* 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 &&
2031 2032
        x86ModelHasSignature(current, signature) &&
        !x86ModelHasSignature(candidate, signature)) {
2033 2034
        VIR_DEBUG("%s differs in signature from matching %s",
                  cpuCandidate->model, cpuCurrent->model);
2035
        return 0;
2036
    }
2037

2038 2039 2040
    if (cpuCurrent->nfeatures > cpuCandidate->nfeatures) {
        VIR_DEBUG("%s results in shorter feature list than %s",
                  cpuCandidate->model, cpuCurrent->model);
2041
        return 1;
2042
    }
2043

2044 2045 2046 2047
    /* Prefer a candidate with matching signature even though it would
     * result in longer list of features.
     */
    if (signature &&
2048 2049
        x86ModelHasSignature(candidate, signature) &&
        !x86ModelHasSignature(current, signature)) {
2050
        VIR_DEBUG("%s provides matching signature", cpuCandidate->model);
2051
        return 1;
2052
    }
2053

2054 2055
    VIR_DEBUG("%s does not result in shorter feature list than %s",
              cpuCandidate->model, cpuCurrent->model);
2056 2057 2058 2059
    return 0;
}


2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
/**
 * 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 已提交
2095 2096
static int
x86Decode(virCPUDefPtr cpu,
2097
          const virCPUx86Data *cpuData,
2098
          virDomainCapsCPUModelsPtr models,
2099
          const char *preferred,
2100
          bool migratable)
J
Jiri Denemark 已提交
2101 2102
{
    int ret = -1;
J
Jiri Denemark 已提交
2103
    virCPUx86MapPtr map;
J
Jiri Denemark 已提交
2104
    virCPUx86ModelPtr candidate;
2105
    virCPUDefPtr cpuCandidate;
2106
    virCPUx86ModelPtr model = NULL;
2107
    virCPUDefPtr cpuModel = NULL;
2108
    virCPUx86Data data = VIR_CPU_X86_DATA_INIT;
2109 2110
    virCPUx86Data copy = VIR_CPU_X86_DATA_INIT;
    virCPUx86Data features = VIR_CPU_X86_DATA_INIT;
J
Jiri Denemark 已提交
2111
    virCPUx86VendorPtr vendor;
2112
    virDomainCapsCPUModelPtr hvModel = NULL;
2113
    g_autofree char *sigs = NULL;
2114
    uint32_t signature;
2115
    ssize_t i;
2116
    int rc;
J
Jiri Denemark 已提交
2117

2118
    if (!cpuData || x86DataCopy(&data, cpuData) < 0)
J
Jiri Denemark 已提交
2119 2120
        return -1;

2121 2122 2123 2124 2125 2126 2127
    if (!(map = virCPUx86GetMap()))
        goto cleanup;

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

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

2129 2130 2131 2132 2133
    /* 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];
2134 2135
        if (models &&
            !(hvModel = virDomainCapsCPUModelsGet(models, candidate->name))) {
2136 2137
            if (preferred && STREQ(candidate->name, preferred)) {
                if (cpu->fallback != VIR_CPU_FALLBACK_ALLOW) {
2138 2139 2140
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("CPU model %s is not supported by hypervisor"),
                                   preferred);
J
Jiri Denemark 已提交
2141
                    goto cleanup;
2142 2143 2144 2145 2146 2147 2148 2149 2150
                } 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);
            }
2151
            continue;
J
Jiri Denemark 已提交
2152 2153
        }

J
Jiri Denemark 已提交
2154 2155 2156 2157
        /* 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 已提交
2158
            VIR_DEBUG("CPU vendor %s of model %s differs from %s; ignoring",
J
Jiri Denemark 已提交
2159
                      candidate->vendor->name, candidate->name, vendor->name);
2160
            continue;
J
Jiri Denemark 已提交
2161 2162
        }

2163
        if (!(cpuCandidate = x86DataToCPU(&data, candidate, map, hvModel)))
J
Jiri Denemark 已提交
2164 2165 2166
            goto cleanup;
        cpuCandidate->type = cpu->type;

2167 2168 2169
        if ((rc = x86DecodeUseCandidate(model, cpuModel,
                                        candidate, cpuCandidate,
                                        signature, preferred,
2170
                                        cpu->type == VIR_CPU_TYPE_HOST))) {
2171 2172
            virCPUDefFree(cpuModel);
            cpuModel = cpuCandidate;
2173
            model = candidate;
2174 2175
            if (rc == 2)
                break;
2176
        } else {
2177
            virCPUDefFree(cpuCandidate);
2178
        }
J
Jiri Denemark 已提交
2179 2180
    }

2181
    if (!cpuModel) {
2182 2183
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("Cannot find suitable CPU model for given data"));
J
Jiri Denemark 已提交
2184
        goto cleanup;
J
Jiri Denemark 已提交
2185 2186
    }

2187 2188 2189
    /* Remove non-migratable features if requested
     * Note: this only works as long as no CPU model contains non-migratable
     * features directly */
2190
    if (migratable) {
2191 2192 2193 2194 2195
        i = 0;
        while (i < cpuModel->nfeatures) {
            if (x86FeatureIsMigratable(cpuModel->features[i].name, map)) {
                i++;
            } else {
2196 2197 2198
                VIR_FREE(cpuModel->features[i].name);
                VIR_DELETE_ELEMENT_INPLACE(cpuModel->features, i,
                                           cpuModel->nfeatures);
2199 2200 2201 2202
            }
        }
    }

2203 2204
    if (vendor)
        cpu->vendor = g_strdup(vendor->name);
J
Jiri Denemark 已提交
2205

2206 2207 2208 2209 2210
    sigs = x86FormatSignatures(model);

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

2211 2212
    cpu->model = g_steal_pointer(&cpuModel->model);
    cpu->features = g_steal_pointer(&cpuModel->features);
2213
    cpu->nfeatures = cpuModel->nfeatures;
2214 2215 2216
    cpuModel->nfeatures = 0;
    cpu->nfeatures_max = cpuModel->nfeatures_max;
    cpuModel->nfeatures_max = 0;
J
Jiri Denemark 已提交
2217 2218 2219

    ret = 0;

J
Jiri Denemark 已提交
2220
 cleanup:
2221
    virCPUDefFree(cpuModel);
2222
    virCPUx86DataClear(&data);
2223 2224
    virCPUx86DataClear(&copy);
    virCPUx86DataClear(&features);
J
Jiri Denemark 已提交
2225 2226 2227
    return ret;
}

2228 2229
static int
x86DecodeCPUData(virCPUDefPtr cpu,
2230
                 const virCPUData *data,
2231
                 virDomainCapsCPUModelsPtr models)
2232
{
2233
    return x86Decode(cpu, &data->data.x86, models, NULL, false);
2234
}
J
Jiri Denemark 已提交
2235

2236

2237 2238 2239
static int
x86EncodePolicy(virCPUx86Data *data,
                const virCPUDef *cpu,
J
Jiri Denemark 已提交
2240
                virCPUx86MapPtr map,
2241
                virCPUFeaturePolicy policy)
J
Jiri Denemark 已提交
2242
{
J
Jiri Denemark 已提交
2243
    virCPUx86ModelPtr model;
J
Jiri Denemark 已提交
2244 2245

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

2248 2249
    *data = model->data;
    model->data.len = 0;
2250
    model->data.items = NULL;
J
Jiri Denemark 已提交
2251 2252
    x86ModelFree(model);

2253
    return 0;
J
Jiri Denemark 已提交
2254 2255 2256 2257
}


static int
J
Jiri Denemark 已提交
2258
x86Encode(virArch arch,
2259
          const virCPUDef *cpu,
2260 2261 2262 2263 2264 2265
          virCPUDataPtr *forced,
          virCPUDataPtr *required,
          virCPUDataPtr *optional,
          virCPUDataPtr *disabled,
          virCPUDataPtr *forbidden,
          virCPUDataPtr *vendor)
J
Jiri Denemark 已提交
2266
{
J
Jiri Denemark 已提交
2267
    virCPUx86MapPtr map = NULL;
2268 2269 2270 2271 2272 2273
    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 已提交
2274

2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
    if (forced)
        *forced = NULL;
    if (required)
        *required = NULL;
    if (optional)
        *optional = NULL;
    if (disabled)
        *disabled = NULL;
    if (forbidden)
        *forbidden = NULL;
    if (vendor)
        *vendor = NULL;

2288
    if (!(map = virCPUx86GetMap()))
J
Jiri Denemark 已提交
2289 2290
        goto error;

2291
    if (forced &&
2292 2293 2294
        (!(data_forced = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_forced->data.x86, cpu, map,
                         VIR_CPU_FEATURE_FORCE) < 0))
2295
        goto error;
J
Jiri Denemark 已提交
2296

2297
    if (required &&
2298 2299 2300
        (!(data_required = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_required->data.x86, cpu, map,
                         VIR_CPU_FEATURE_REQUIRE) < 0))
2301
        goto error;
J
Jiri Denemark 已提交
2302

2303
    if (optional &&
2304 2305 2306
        (!(data_optional = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_optional->data.x86, cpu, map,
                         VIR_CPU_FEATURE_OPTIONAL) < 0))
2307
        goto error;
J
Jiri Denemark 已提交
2308

2309
    if (disabled &&
2310 2311 2312
        (!(data_disabled = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_disabled->data.x86, cpu, map,
                         VIR_CPU_FEATURE_DISABLE) < 0))
2313
        goto error;
J
Jiri Denemark 已提交
2314

2315
    if (forbidden &&
2316 2317 2318
        (!(data_forbidden = virCPUDataNew(arch)) ||
         x86EncodePolicy(&data_forbidden->data.x86, cpu, map,
                         VIR_CPU_FEATURE_FORBID) < 0))
2319
        goto error;
J
Jiri Denemark 已提交
2320

J
Jiri Denemark 已提交
2321
    if (vendor) {
2322
        virCPUx86VendorPtr v = NULL;
J
Jiri Denemark 已提交
2323 2324

        if (cpu->vendor && !(v = x86VendorFind(map, cpu->vendor))) {
2325 2326
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("CPU vendor %s not found"), cpu->vendor);
J
Jiri Denemark 已提交
2327 2328 2329
            goto error;
        }

2330
        if (!(data_vendor = virCPUDataNew(arch)))
J
Jiri Denemark 已提交
2331 2332
            goto error;

2333
        if (v && virCPUx86DataAdd(data_vendor, &v->data) < 0)
2334 2335
            goto error;
    }
J
Jiri Denemark 已提交
2336

2337
    if (forced)
2338
        *forced = data_forced;
2339
    if (required)
2340
        *required = data_required;
2341
    if (optional)
2342
        *optional = data_optional;
2343
    if (disabled)
2344
        *disabled = data_disabled;
2345
    if (forbidden)
2346
        *forbidden = data_forbidden;
2347
    if (vendor)
2348 2349 2350 2351 2352
        *vendor = data_vendor;

    return 0;

 error:
J
Jiri Denemark 已提交
2353 2354 2355 2356 2357 2358
    virCPUx86DataFree(data_forced);
    virCPUx86DataFree(data_required);
    virCPUx86DataFree(data_optional);
    virCPUx86DataFree(data_disabled);
    virCPUx86DataFree(data_forbidden);
    virCPUx86DataFree(data_vendor);
2359
    return -1;
J
Jiri Denemark 已提交
2360 2361 2362
}


2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
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;
}


static int
virCPUx86DataCheckFeature(const virCPUData *data,
                          const char *name)
{
    virCPUx86MapPtr map;

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

    return x86FeatureInData(name, &data->data.x86, map);
}


P
Pavel Hrdina 已提交
2398
#if defined(__i386__) || defined(__x86_64__)
J
Jiri Denemark 已提交
2399
static inline void
2400
cpuidCall(virCPUx86CPUID *cpuid)
J
Jiri Denemark 已提交
2401
{
2402
# if __x86_64__
2403
    asm("xor %%ebx, %%ebx;" /* clear the other registers as some cpuid */
2404
        "xor %%edx, %%edx;" /* functions may use them as additional arguments */
2405
        "cpuid;"
J
Jiri Denemark 已提交
2406 2407 2408 2409
        : "=a" (cpuid->eax),
          "=b" (cpuid->ebx),
          "=c" (cpuid->ecx),
          "=d" (cpuid->edx)
2410 2411
        : "a" (cpuid->eax_in),
          "c" (cpuid->ecx_in));
2412
# else
J
Jiri Denemark 已提交
2413 2414 2415 2416
    /* 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;"
2417
        "xor %%ebx, %%ebx;" /* clear the other registers as some cpuid */
2418
        "xor %%edx, %%edx;" /* functions may use them as additional arguments */
J
Jiri Denemark 已提交
2419 2420 2421 2422 2423 2424 2425
        "cpuid;"
        "mov %%ebx, %1;"
        "pop %%ebx;"
        : "=a" (cpuid->eax),
          "=r" (cpuid->ebx),
          "=c" (cpuid->ecx),
          "=d" (cpuid->edx)
2426 2427
        : "a" (cpuid->eax_in),
          "c" (cpuid->ecx_in)
J
Jiri Denemark 已提交
2428
        : "cc");
2429
# endif
J
Jiri Denemark 已提交
2430 2431 2432
}


2433 2434 2435 2436 2437
/* Leaf 0x04: deterministic cache parameters
 *
 * Sub leaf n+1 is invalid if eax[4:0] in sub leaf n equals 0.
 */
static int
2438
cpuidSetLeaf4(virCPUDataPtr data,
2439
              virCPUx86DataItemPtr subLeaf0)
2440
{
2441
    virCPUx86DataItem item = *subLeaf0;
2442
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2443

2444
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2445 2446
        return -1;

2447 2448 2449
    while (cpuid->eax & 0x1f) {
        cpuid->ecx_in++;
        cpuidCall(cpuid);
2450
        if (virCPUx86DataAdd(data, &item) < 0)
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
            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
2462
cpuidSetLeaf7(virCPUDataPtr data,
2463
              virCPUx86DataItemPtr subLeaf0)
2464
{
2465
    virCPUx86DataItem item = CPUID(.eax_in = 0x7);
2466
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2467 2468
    uint32_t sub;

2469
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2470 2471
        return -1;

2472
    for (sub = 1; sub <= subLeaf0->data.cpuid.eax; sub++) {
2473 2474
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2475
        if (virCPUx86DataAdd(data, &item) < 0)
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
            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
2490
cpuidSetLeafB(virCPUDataPtr data,
2491
              virCPUx86DataItemPtr subLeaf0)
2492
{
2493
    virCPUx86DataItem item = *subLeaf0;
2494
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2495

2496
    while (cpuid->ecx & 0xff00) {
2497
        if (virCPUx86DataAdd(data, &item) < 0)
2498
            return -1;
2499 2500
        cpuid->ecx_in++;
        cpuidCall(cpuid);
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
    }
    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
2515
cpuidSetLeafD(virCPUDataPtr data,
2516
              virCPUx86DataItemPtr subLeaf0)
2517
{
2518
    virCPUx86DataItem item = CPUID(.eax_in = 0xd);
2519
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2520 2521 2522 2523
    virCPUx86CPUID sub0;
    virCPUx86CPUID sub1;
    uint32_t sub;

2524
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2525 2526
        return -1;

2527 2528
    cpuid->ecx_in = 1;
    cpuidCall(cpuid);
2529
    if (virCPUx86DataAdd(data, &item) < 0)
2530 2531
        return -1;

2532
    sub0 = subLeaf0->data.cpuid;
2533
    sub1 = *cpuid;
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
    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;

2544 2545
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2546
        if (virCPUx86DataAdd(data, &item) < 0)
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
            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
2563
cpuidSetLeafResID(virCPUDataPtr data,
2564
                  virCPUx86DataItemPtr subLeaf0,
2565 2566
                  uint32_t res)
{
2567 2568
    virCPUx86DataItem item = CPUID(.eax_in = subLeaf0->data.cpuid.eax_in);
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2569 2570
    uint32_t sub;

2571
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2572 2573 2574 2575 2576
        return -1;

    for (sub = 1; sub < 32; sub++) {
        if (!(res & (1 << sub)))
            continue;
2577 2578
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2579
        if (virCPUx86DataAdd(data, &item) < 0)
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
            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
2592
cpuidSetLeaf12(virCPUDataPtr data,
2593
               virCPUx86DataItemPtr subLeaf0)
2594
{
2595
    virCPUx86DataItem item = CPUID(.eax_in = 0x7);
2596
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2597
    virCPUx86DataItemPtr leaf7;
2598

J
Jiri Denemark 已提交
2599
    if (!(leaf7 = virCPUx86DataGet(&data->data.x86, &item)) ||
2600
        !(leaf7->data.cpuid.ebx & (1 << 2)))
2601 2602
        return 0;

2603
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2604 2605
        return -1;

2606 2607 2608
    cpuid->eax_in = 0x12;
    cpuid->ecx_in = 1;
    cpuidCall(cpuid);
2609
    if (virCPUx86DataAdd(data, &item) < 0)
2610 2611
        return -1;

2612 2613 2614
    cpuid->ecx_in = 2;
    cpuidCall(cpuid);
    while (cpuid->eax & 0xf) {
2615
        if (virCPUx86DataAdd(data, &item) < 0)
2616
            return -1;
2617 2618
        cpuid->ecx_in++;
        cpuidCall(cpuid);
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
    }
    return 0;
}


/* Leaf 0x14: processor trace enumeration
 *
 * Sub leaf 0 reports the maximum supported sub leaf in eax.
 */
static int
2629
cpuidSetLeaf14(virCPUDataPtr data,
2630
               virCPUx86DataItemPtr subLeaf0)
2631
{
2632
    virCPUx86DataItem item = CPUID(.eax_in = 0x14);
2633
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2634 2635
    uint32_t sub;

2636
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2637 2638
        return -1;

2639
    for (sub = 1; sub <= subLeaf0->data.cpuid.eax; sub++) {
2640 2641
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2642
        if (virCPUx86DataAdd(data, &item) < 0)
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
            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
2655
cpuidSetLeaf17(virCPUDataPtr data,
2656
               virCPUx86DataItemPtr subLeaf0)
2657
{
2658
    virCPUx86DataItem item = CPUID(.eax_in = 0x17);
2659
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
2660 2661
    uint32_t sub;

2662
    if (subLeaf0->data.cpuid.eax < 3)
2663 2664
        return 0;

2665
    if (virCPUx86DataAdd(data, subLeaf0) < 0)
2666 2667
        return -1;

2668
    for (sub = 1; sub <= subLeaf0->data.cpuid.eax; sub++) {
2669 2670
        cpuid->ecx_in = sub;
        cpuidCall(cpuid);
2671
        if (virCPUx86DataAdd(data, &item) < 0)
2672 2673 2674 2675 2676 2677
            return -1;
    }
    return 0;
}


J
Jiri Denemark 已提交
2678
static int
2679
cpuidSet(uint32_t base, virCPUDataPtr data)
J
Jiri Denemark 已提交
2680
{
2681
    int rc;
J
Jiri Denemark 已提交
2682
    uint32_t max;
2683
    uint32_t leaf;
2684
    virCPUx86DataItem item = CPUID(.eax_in = base);
2685
    virCPUx86CPUIDPtr cpuid = &item.data.cpuid;
J
Jiri Denemark 已提交
2686

2687 2688
    cpuidCall(cpuid);
    max = cpuid->eax;
J
Jiri Denemark 已提交
2689

2690
    for (leaf = base; leaf <= max; leaf++) {
2691 2692 2693
        cpuid->eax_in = leaf;
        cpuid->ecx_in = 0;
        cpuidCall(cpuid);
2694 2695 2696 2697 2698

        /* Handle CPUID leaves that depend on previously queried bits or
         * which provide additional sub leaves for ecx_in > 0
         */
        if (leaf == 0x4)
2699
            rc = cpuidSetLeaf4(data, &item);
2700
        else if (leaf == 0x7)
2701
            rc = cpuidSetLeaf7(data, &item);
2702
        else if (leaf == 0xb)
2703
            rc = cpuidSetLeafB(data, &item);
2704
        else if (leaf == 0xd)
2705
            rc = cpuidSetLeafD(data, &item);
2706
        else if (leaf == 0xf)
2707
            rc = cpuidSetLeafResID(data, &item, cpuid->edx);
2708
        else if (leaf == 0x10)
2709
            rc = cpuidSetLeafResID(data, &item, cpuid->ebx);
2710
        else if (leaf == 0x12)
2711
            rc = cpuidSetLeaf12(data, &item);
2712
        else if (leaf == 0x14)
2713
            rc = cpuidSetLeaf14(data, &item);
2714
        else if (leaf == 0x17)
2715
            rc = cpuidSetLeaf17(data, &item);
2716
        else
2717
            rc = virCPUx86DataAdd(data, &item);
2718 2719

        if (rc < 0)
2720
            return -1;
J
Jiri Denemark 已提交
2721 2722
    }

2723
    return 0;
J
Jiri Denemark 已提交
2724 2725 2726
}


2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
static int
virCPUx86GetHost(virCPUDefPtr cpu,
                 virDomainCapsCPUModelsPtr models)
{
    virCPUDataPtr cpuData = NULL;
    int ret = -1;

    if (virCPUx86DriverInitialize() < 0)
        goto cleanup;

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

    if (cpuidSet(CPUX86_BASIC, cpuData) < 0 ||
        cpuidSet(CPUX86_EXTENDED, cpuData) < 0)
        goto cleanup;

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
    /* Read the IA32_ARCH_CAPABILITIES MSR (0x10a) if supported.
     * This is best effort since there might be no way to read the MSR
     * when we are not running as root. */
    if (virCPUx86DataCheckFeature(cpuData, "arch-capabilities") == 1) {
        uint64_t msr;
        unsigned long index = 0x10a;

        if (virHostCPUGetMSR(index, &msr) == 0) {
            virCPUx86DataItem item = {
                .type = VIR_CPU_X86_DATA_MSR,
                .data.msr = {
                    .index = index,
                    .eax = msr & 0xffffffff,
                    .edx = msr >> 32,
                },
            };

            if (virCPUx86DataAdd(cpuData, &item) < 0)
2762
                goto cleanup;
2763 2764 2765
        }
    }

2766 2767 2768
    ret = x86DecodeCPUData(cpu, cpuData, models);
    cpu->microcodeVersion = virHostCPUGetMicrocodeVersion();

2769 2770 2771 2772 2773 2774 2775 2776 2777
    /* Probing for TSC frequency makes sense only if the CPU supports
     * invariant TSC (Linux calls this constant_tsc in /proc/cpuinfo). */
    if (virCPUx86DataCheckFeature(cpuData, "invtsc") == 1) {
        VIR_DEBUG("Checking invariant TSC frequency");
        cpu->tsc = virHostCPUGetTscInfo();
    } else {
        VIR_DEBUG("Host CPU does not support invariant TSC");
    }

2778 2779 2780 2781 2782 2783 2784
 cleanup:
    virCPUx86DataFree(cpuData);
    return ret;
}
#endif


2785
static virCPUDefPtr
2786 2787 2788
virCPUx86Baseline(virCPUDefPtr *cpus,
                  unsigned int ncpus,
                  virDomainCapsCPUModelsPtr models,
2789
                  const char **features,
2790
                  bool migratable)
2791
{
J
Jiri Denemark 已提交
2792
    virCPUx86MapPtr map = NULL;
J
Jiri Denemark 已提交
2793
    virCPUx86ModelPtr base_model = NULL;
2794
    virCPUDefPtr cpu = NULL;
2795
    size_t i;
2796
    virCPUx86VendorPtr vendor = NULL;
J
Jiri Denemark 已提交
2797
    virCPUx86ModelPtr model = NULL;
2798
    bool outputVendor = true;
2799 2800
    const char *modelName;
    bool matchingNames = true;
2801
    virCPUDataPtr featData = NULL;
2802

2803
    if (!(map = virCPUx86GetMap()))
2804 2805
        goto error;

2806
    if (!(base_model = x86ModelFromCPU(cpus[0], map, -1)))
2807 2808
        goto error;

2809
    cpu = virCPUDefNew();
2810

2811 2812
    cpu->type = VIR_CPU_TYPE_GUEST;
    cpu->match = VIR_CPU_MATCH_EXACT;
2813

2814
    if (!cpus[0]->vendor) {
2815
        outputVendor = false;
2816
    } else if (!(vendor = x86VendorFind(map, cpus[0]->vendor))) {
2817 2818
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unknown CPU vendor %s"), cpus[0]->vendor);
J
Jiri Denemark 已提交
2819 2820 2821
        goto error;
    }

2822
    modelName = cpus[0]->model;
2823
    for (i = 1; i < ncpus; i++) {
J
Jiri Denemark 已提交
2824 2825
        const char *vn = NULL;

2826 2827 2828 2829 2830 2831 2832 2833 2834
        if (matchingNames && cpus[i]->model) {
            if (!modelName) {
                modelName = cpus[i]->model;
            } else if (STRNEQ(modelName, cpus[i]->model)) {
                modelName = NULL;
                matchingNames = false;
            }
        }

2835
        if (!(model = x86ModelFromCPU(cpus[i], map, -1)))
2836 2837
            goto error;

J
Jiri Denemark 已提交
2838 2839
        if (cpus[i]->vendor && model->vendor &&
            STRNEQ(cpus[i]->vendor, model->vendor->name)) {
2840 2841 2842
            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 已提交
2843 2844 2845
            goto error;
        }

2846
        if (cpus[i]->vendor) {
J
Jiri Denemark 已提交
2847
            vn = cpus[i]->vendor;
2848
        } else {
2849 2850 2851 2852
            outputVendor = false;
            if (model->vendor)
                vn = model->vendor->name;
        }
J
Jiri Denemark 已提交
2853 2854 2855 2856

        if (vn) {
            if (!vendor) {
                if (!(vendor = x86VendorFind(map, vn))) {
2857 2858
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("Unknown CPU vendor %s"), vn);
J
Jiri Denemark 已提交
2859 2860 2861
                    goto error;
                }
            } else if (STRNEQ(vendor->name, vn)) {
2862 2863
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("CPU vendors do not match"));
J
Jiri Denemark 已提交
2864 2865 2866 2867
                goto error;
            }
        }

2868
        x86DataIntersect(&base_model->data, &model->data);
2869
        x86ModelFree(model);
J
Jiri Denemark 已提交
2870
        model = NULL;
2871 2872
    }

2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
    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);
    }

2888
    if (x86DataIsEmpty(&base_model->data)) {
2889 2890
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("CPUs are incompatible"));
2891 2892 2893
        goto error;
    }

2894
    if (vendor &&
2895
        virCPUx86DataAddItem(&base_model->data, &vendor->data) < 0)
2896
        goto error;
J
Jiri Denemark 已提交
2897

2898
    if (x86Decode(cpu, &base_model->data, models, modelName, migratable) < 0)
2899 2900
        goto error;

2901 2902 2903
    if (STREQ_NULLABLE(cpu->model, modelName))
        cpu->fallback = VIR_CPU_FALLBACK_FORBID;

2904 2905 2906
    if (!outputVendor)
        VIR_FREE(cpu->vendor);

2907
 cleanup:
2908
    x86ModelFree(base_model);
2909
    virCPUx86DataFree(featData);
2910 2911 2912

    return cpu;

2913
 error:
J
Jiri Denemark 已提交
2914
    x86ModelFree(model);
2915 2916 2917 2918 2919 2920
    virCPUDefFree(cpu);
    cpu = NULL;
    goto cleanup;
}


2921
static int
J
Jiri Denemark 已提交
2922
x86UpdateHostModel(virCPUDefPtr guest,
2923
                   const virCPUDef *host)
2924
{
J
Jiri Denemark 已提交
2925
    virCPUDefPtr updated = NULL;
2926
    size_t i;
J
Jiri Denemark 已提交
2927
    int ret = -1;
2928

J
Jiri Denemark 已提交
2929
    if (!(updated = virCPUDefCopyWithoutModel(host)))
2930 2931
        goto cleanup;

J
Jiri Denemark 已提交
2932 2933
    updated->type = VIR_CPU_TYPE_GUEST;
    updated->mode = VIR_CPU_MODE_CUSTOM;
2934
    if (virCPUDefCopyModel(updated, host, true) < 0)
J
Jiri Denemark 已提交
2935
        goto cleanup;
2936

J
Jiri Denemark 已提交
2937 2938
    if (guest->vendor_id) {
        VIR_FREE(updated->vendor_id);
2939
        updated->vendor_id = g_strdup(guest->vendor_id);
J
Jiri Denemark 已提交
2940 2941 2942 2943 2944 2945
    }

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

2949 2950
    virCPUDefStealModel(guest, updated,
                        guest->mode == VIR_CPU_MODE_CUSTOM);
J
Jiri Denemark 已提交
2951 2952
    guest->mode = VIR_CPU_MODE_CUSTOM;
    guest->match = VIR_CPU_MATCH_EXACT;
2953 2954
    ret = 0;

2955
 cleanup:
J
Jiri Denemark 已提交
2956
    virCPUDefFree(updated);
2957 2958 2959
    return ret;
}

2960 2961

static int
J
Jiri Denemark 已提交
2962 2963
virCPUx86Update(virCPUDefPtr guest,
                const virCPUDef *host)
2964
{
J
Jiri Denemark 已提交
2965
    virCPUx86ModelPtr model = NULL;
J
Jiri Denemark 已提交
2966
    virCPUx86MapPtr map;
2967
    int ret = -1;
J
Jiri Denemark 已提交
2968
    size_t i;
2969

J
Jiri Denemark 已提交
2970 2971 2972 2973 2974
    if (!host) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("unknown host CPU model"));
        return -1;
    }
2975

J
Jiri Denemark 已提交
2976 2977
    if (!(map = virCPUx86GetMap()))
        return -1;
2978

J
Jiri Denemark 已提交
2979
    if (!(model = x86ModelFromCPU(host, map, -1)))
2980
        goto cleanup;
2981

J
Jiri Denemark 已提交
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
    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;
2992 2993
        }
    }
2994

J
Jiri Denemark 已提交
2995 2996
    if (guest->mode == VIR_CPU_MODE_HOST_MODEL ||
        guest->match == VIR_CPU_MATCH_MINIMUM)
2997
        ret = x86UpdateHostModel(guest, host);
J
Jiri Denemark 已提交
2998 2999
    else
        ret = 0;
3000 3001

 cleanup:
J
Jiri Denemark 已提交
3002
    x86ModelFree(model);
3003
    return ret;
3004 3005 3006
}


3007 3008 3009 3010 3011 3012 3013 3014 3015
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;
3016 3017 3018 3019
    virBuffer bufAdded = VIR_BUFFER_INITIALIZER;
    virBuffer bufRemoved = VIR_BUFFER_INITIALIZER;
    char *added = NULL;
    char *removed = NULL;
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038
    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];
3039
        virCPUFeaturePolicy expected = VIR_CPU_FEATURE_LAST;
3040

3041 3042 3043 3044 3045 3046 3047
        if (x86DataIsSubset(&model->data, &feature->data))
            expected = VIR_CPU_FEATURE_REQUIRE;
        else
            expected = VIR_CPU_FEATURE_DISABLE;

        if (expected == VIR_CPU_FEATURE_DISABLE &&
            x86DataIsSubset(&enabled, &feature->data)) {
3048 3049 3050 3051 3052
            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)
3053 3054 3055
                goto cleanup;
        }

3056
        if (x86DataIsSubset(&disabled, &feature->data) ||
3057
            (expected == VIR_CPU_FEATURE_REQUIRE &&
3058
             !x86DataIsSubset(&enabled, &feature->data))) {
3059 3060 3061 3062 3063
            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)
3064 3065 3066 3067
                goto cleanup;
        }
    }

J
Ján Tomko 已提交
3068 3069
    virBufferTrim(&bufAdded, ",");
    virBufferTrim(&bufRemoved, ",");
3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099

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

3100 3101 3102 3103 3104 3105
    ret = 0;

 cleanup:
    x86ModelFree(model);
    virCPUx86DataClear(&enabled);
    virCPUx86DataClear(&disabled);
3106 3107 3108 3109
    VIR_FREE(added);
    VIR_FREE(removed);
    virBufferFreeAndReset(&bufAdded);
    virBufferFreeAndReset(&bufRemoved);
3110 3111 3112 3113
    return ret;
}


3114
static int
J
Jiri Denemark 已提交
3115
virCPUx86GetModels(char ***models)
3116
{
J
Jiri Denemark 已提交
3117
    virCPUx86MapPtr map;
3118
    size_t i;
3119 3120 3121 3122

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

3123 3124 3125
    if (models) {
        if (VIR_ALLOC_N(*models, map->nmodels + 1) < 0)
            goto error;
3126

3127 3128
        for (i = 0; i < map->nmodels; i++)
            (*models)[i] = g_strdup(map->models[i]->name);
3129 3130
    }

3131
    return map->nmodels;
3132 3133

 error:
3134
    if (models) {
3135
        virStringListFree(*models);
3136 3137
        *models = NULL;
    }
3138 3139 3140
    return -1;
}

3141

J
Jiri Denemark 已提交
3142 3143
static int
virCPUx86Translate(virCPUDefPtr cpu,
3144
                   virDomainCapsCPUModelsPtr models)
J
Jiri Denemark 已提交
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
{
    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 &&
3159
        virCPUx86DataAddItem(&model->data, &model->vendor->data) < 0)
J
Jiri Denemark 已提交
3160 3161
        goto cleanup;

3162 3163
    if (model->signatures &&
        x86DataAddSignature(&model->data, model->signatures[0]) < 0)
J
Jiri Denemark 已提交
3164 3165 3166 3167 3168
        goto cleanup;

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

3169
    if (x86Decode(translated, &model->data, models, NULL, false) < 0)
J
Jiri Denemark 已提交
3170 3171 3172 3173 3174 3175 3176 3177
        goto cleanup;

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

3178
    virCPUDefStealModel(cpu, translated, true);
J
Jiri Denemark 已提交
3179 3180 3181 3182 3183 3184 3185 3186 3187
    ret = 0;

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


3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239
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;
}


3240 3241 3242 3243 3244 3245 3246 3247 3248
static bool
x86FeatureFilterMigratable(const char *name,
                           virCPUFeaturePolicy policy G_GNUC_UNUSED,
                           void *cpu_map)
{
    return x86FeatureIsMigratable(name, cpu_map);
}


3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
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,
3262
                                 x86FeatureFilterMigratable, map) < 0)
3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
        goto error;

    return copy;

 error:
    virCPUDefFree(copy);
    return NULL;
}


3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
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;
}


3295
int
3296 3297
virCPUx86DataAdd(virCPUDataPtr cpuData,
                 const virCPUx86DataItem *item)
3298
{
3299
    return virCPUx86DataAddItem(&cpuData->data.x86, item);
3300 3301 3302
}


3303 3304 3305
int
virCPUx86DataSetSignature(virCPUDataPtr cpuData,
                          unsigned int family,
3306 3307
                          unsigned int model,
                          unsigned int stepping)
3308
{
3309
    uint32_t signature = x86MakeSignature(family, model, stepping);
3310 3311 3312 3313 3314

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


3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326
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);
}


3327 3328 3329 3330
int
virCPUx86DataSetVendor(virCPUDataPtr cpuData,
                       const char *vendor)
{
3331
    virCPUx86DataItem item = CPUID(0);
3332

3333
    if (virCPUx86VendorToData(vendor, &item) < 0)
3334 3335
        return -1;

3336
    return virCPUx86DataAdd(cpuData, &item);
3337 3338 3339
}


3340
static int
3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
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;
}


3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396
static bool
virCPUx86FeatureIsMSR(const char *name)
{
    virCPUx86FeaturePtr feature;
    virCPUx86DataIterator iter;
    virCPUx86DataItemPtr item;
    virCPUx86MapPtr map;

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

    if (!(feature = x86FeatureFind(map, name)) &&
        !(feature = x86FeatureFindInternal(name)))
        return false;

    virCPUx86DataIteratorInit(&iter, &feature->data);
    while ((item = virCPUx86DataNext(&iter))) {
        if (item->type == VIR_CPU_X86_DATA_MSR)
            return true;
    }

    return false;
}


/**
 * virCPUx86FeatureFilterSelectMSR:
 *
 * This is a callback for functions filtering features in virCPUDef. The result
 * will contain only MSR features.
 *
 * Returns true if @name is an MSR feature, false otherwise.
 */
bool
virCPUx86FeatureFilterSelectMSR(const char *name,
3397
                                virCPUFeaturePolicy policy G_GNUC_UNUSED,
J
Ján Tomko 已提交
3398
                                void *opaque G_GNUC_UNUSED)
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
{
    return virCPUx86FeatureIsMSR(name);
}


/**
 * virCPUx86FeatureFilterDropMSR:
 *
 * This is a callback for functions filtering features in virCPUDef. The result
 * will not contain any MSR feature.
 *
 * Returns true if @name is not an MSR feature, false otherwise.
 */
bool
virCPUx86FeatureFilterDropMSR(const char *name,
3414
                              virCPUFeaturePolicy policy G_GNUC_UNUSED,
J
Ján Tomko 已提交
3415
                              void *opaque G_GNUC_UNUSED)
3416 3417 3418 3419 3420
{
    return !virCPUx86FeatureIsMSR(name);
}


J
Jiri Denemark 已提交
3421 3422 3423
struct cpuArchDriver cpuDriverX86 = {
    .name = "x86",
    .arch = archs,
3424
    .narch = G_N_ELEMENTS(archs),
J
Jiri Denemark 已提交
3425
    .compare    = virCPUx86Compare,
3426
    .decode     = x86DecodeCPUData,
J
Jiri Denemark 已提交
3427
    .encode     = x86Encode,
J
Jiri Denemark 已提交
3428
    .dataFree   = virCPUx86DataFree,
P
Pavel Hrdina 已提交
3429
#if defined(__i386__) || defined(__x86_64__)
3430
    .getHost    = virCPUx86GetHost,
J
Jiri Denemark 已提交
3431
#endif
3432
    .baseline   = virCPUx86Baseline,
J
Jiri Denemark 已提交
3433
    .update     = virCPUx86Update,
3434
    .updateLive = virCPUx86UpdateLive,
3435
    .checkFeature = virCPUx86CheckFeature,
3436
    .dataCheckFeature = virCPUx86DataCheckFeature,
J
Jiri Denemark 已提交
3437
    .dataFormat = virCPUx86DataFormat,
J
Jiri Denemark 已提交
3438
    .dataParse  = virCPUx86DataParse,
J
Jiri Denemark 已提交
3439
    .getModels  = virCPUx86GetModels,
J
Jiri Denemark 已提交
3440
    .translate  = virCPUx86Translate,
3441
    .expandFeatures = virCPUx86ExpandFeatures,
3442
    .copyMigratable = virCPUx86CopyMigratable,
3443
    .validateFeatures = virCPUx86ValidateFeatures,
3444
    .dataAddFeature = virCPUx86DataAddFeature,
J
Jiri Denemark 已提交
3445
};