qemu/hw/i386/x86.c
<<
>>
Prefs
   1/*
   2 * Copyright (c) 2003-2004 Fabrice Bellard
   3 * Copyright (c) 2019 Red Hat, Inc.
   4 *
   5 * Permission is hereby granted, free of charge, to any person obtaining a copy
   6 * of this software and associated documentation files (the "Software"), to deal
   7 * in the Software without restriction, including without limitation the rights
   8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   9 * copies of the Software, and to permit persons to whom the Software is
  10 * furnished to do so, subject to the following conditions:
  11 *
  12 * The above copyright notice and this permission notice shall be included in
  13 * all copies or substantial portions of the Software.
  14 *
  15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21 * THE SOFTWARE.
  22 */
  23#include "qemu/osdep.h"
  24#include "qemu/error-report.h"
  25#include "qemu/option.h"
  26#include "qemu/cutils.h"
  27#include "qemu/units.h"
  28#include "qemu-common.h"
  29#include "qemu/datadir.h"
  30#include "qapi/error.h"
  31#include "qapi/qmp/qerror.h"
  32#include "qapi/qapi-visit-common.h"
  33#include "qapi/clone-visitor.h"
  34#include "qapi/qapi-visit-machine.h"
  35#include "qapi/visitor.h"
  36#include "sysemu/qtest.h"
  37#include "sysemu/whpx.h"
  38#include "sysemu/numa.h"
  39#include "sysemu/replay.h"
  40#include "sysemu/sysemu.h"
  41#include "sysemu/cpu-timers.h"
  42#include "trace.h"
  43
  44#include "hw/i386/x86.h"
  45#include "target/i386/cpu.h"
  46#include "hw/i386/topology.h"
  47#include "hw/i386/fw_cfg.h"
  48#include "hw/intc/i8259.h"
  49#include "hw/rtc/mc146818rtc.h"
  50#include "target/i386/sev.h"
  51
  52#include "hw/acpi/cpu_hotplug.h"
  53#include "hw/irq.h"
  54#include "hw/nmi.h"
  55#include "hw/loader.h"
  56#include "multiboot.h"
  57#include "elf.h"
  58#include "standard-headers/asm-x86/bootparam.h"
  59#include CONFIG_DEVICES
  60#include "kvm/kvm_i386.h"
  61
  62/* Physical Address of PVH entry point read from kernel ELF NOTE */
  63static size_t pvh_start_addr;
  64
  65inline void init_topo_info(X86CPUTopoInfo *topo_info,
  66                           const X86MachineState *x86ms)
  67{
  68    MachineState *ms = MACHINE(x86ms);
  69
  70    topo_info->dies_per_pkg = ms->smp.dies;
  71    topo_info->cores_per_die = ms->smp.cores;
  72    topo_info->threads_per_core = ms->smp.threads;
  73}
  74
  75/*
  76 * Calculates initial APIC ID for a specific CPU index
  77 *
  78 * Currently we need to be able to calculate the APIC ID from the CPU index
  79 * alone (without requiring a CPU object), as the QEMU<->Seabios interfaces have
  80 * no concept of "CPU index", and the NUMA tables on fw_cfg need the APIC ID of
  81 * all CPUs up to max_cpus.
  82 */
  83uint32_t x86_cpu_apic_id_from_index(X86MachineState *x86ms,
  84                                    unsigned int cpu_index)
  85{
  86    X86MachineClass *x86mc = X86_MACHINE_GET_CLASS(x86ms);
  87    X86CPUTopoInfo topo_info;
  88    uint32_t correct_id;
  89    static bool warned;
  90
  91    init_topo_info(&topo_info, x86ms);
  92
  93    correct_id = x86_apicid_from_cpu_idx(&topo_info, cpu_index);
  94    if (x86mc->compat_apic_id_mode) {
  95        if (cpu_index != correct_id && !warned && !qtest_enabled()) {
  96            error_report("APIC IDs set in compatibility mode, "
  97                         "CPU topology won't match the configuration");
  98            warned = true;
  99        }
 100        return cpu_index;
 101    } else {
 102        return correct_id;
 103    }
 104}
 105
 106
 107void x86_cpu_new(X86MachineState *x86ms, int64_t apic_id, Error **errp)
 108{
 109    Object *cpu = object_new(MACHINE(x86ms)->cpu_type);
 110
 111    if (!object_property_set_uint(cpu, "apic-id", apic_id, errp)) {
 112        goto out;
 113    }
 114    qdev_realize(DEVICE(cpu), NULL, errp);
 115
 116out:
 117    object_unref(cpu);
 118}
 119
 120void x86_cpus_init(X86MachineState *x86ms, int default_cpu_version)
 121{
 122    int i;
 123    const CPUArchIdList *possible_cpus;
 124    MachineState *ms = MACHINE(x86ms);
 125    MachineClass *mc = MACHINE_GET_CLASS(x86ms);
 126
 127    x86_cpu_set_default_version(default_cpu_version);
 128
 129    /*
 130     * Calculates the limit to CPU APIC ID values
 131     *
 132     * Limit for the APIC ID value, so that all
 133     * CPU APIC IDs are < x86ms->apic_id_limit.
 134     *
 135     * This is used for FW_CFG_MAX_CPUS. See comments on fw_cfg_arch_create().
 136     */
 137    x86ms->apic_id_limit = x86_cpu_apic_id_from_index(x86ms,
 138                                                      ms->smp.max_cpus - 1) + 1;
 139    possible_cpus = mc->possible_cpu_arch_ids(ms);
 140    for (i = 0; i < ms->smp.cpus; i++) {
 141        x86_cpu_new(x86ms, possible_cpus->cpus[i].arch_id, &error_fatal);
 142    }
 143}
 144
 145void x86_rtc_set_cpus_count(ISADevice *rtc, uint16_t cpus_count)
 146{
 147    if (cpus_count > 0xff) {
 148        /*
 149         * If the number of CPUs can't be represented in 8 bits, the
 150         * BIOS must use "FW_CFG_NB_CPUS". Set RTC field to 0 just
 151         * to make old BIOSes fail more predictably.
 152         */
 153        rtc_set_memory(rtc, 0x5f, 0);
 154    } else {
 155        rtc_set_memory(rtc, 0x5f, cpus_count - 1);
 156    }
 157}
 158
 159static int x86_apic_cmp(const void *a, const void *b)
 160{
 161   CPUArchId *apic_a = (CPUArchId *)a;
 162   CPUArchId *apic_b = (CPUArchId *)b;
 163
 164   return apic_a->arch_id - apic_b->arch_id;
 165}
 166
 167/*
 168 * returns pointer to CPUArchId descriptor that matches CPU's apic_id
 169 * in ms->possible_cpus->cpus, if ms->possible_cpus->cpus has no
 170 * entry corresponding to CPU's apic_id returns NULL.
 171 */
 172CPUArchId *x86_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
 173{
 174    CPUArchId apic_id, *found_cpu;
 175
 176    apic_id.arch_id = id;
 177    found_cpu = bsearch(&apic_id, ms->possible_cpus->cpus,
 178        ms->possible_cpus->len, sizeof(*ms->possible_cpus->cpus),
 179        x86_apic_cmp);
 180    if (found_cpu && idx) {
 181        *idx = found_cpu - ms->possible_cpus->cpus;
 182    }
 183    return found_cpu;
 184}
 185
 186void x86_cpu_plug(HotplugHandler *hotplug_dev,
 187                  DeviceState *dev, Error **errp)
 188{
 189    CPUArchId *found_cpu;
 190    Error *local_err = NULL;
 191    X86CPU *cpu = X86_CPU(dev);
 192    X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
 193
 194    if (x86ms->acpi_dev) {
 195        hotplug_handler_plug(x86ms->acpi_dev, dev, &local_err);
 196        if (local_err) {
 197            goto out;
 198        }
 199    }
 200
 201    /* increment the number of CPUs */
 202    x86ms->boot_cpus++;
 203    if (x86ms->rtc) {
 204        x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
 205    }
 206    if (x86ms->fw_cfg) {
 207        fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
 208    }
 209
 210    found_cpu = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, NULL);
 211    found_cpu->cpu = OBJECT(dev);
 212out:
 213    error_propagate(errp, local_err);
 214}
 215
 216void x86_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
 217                               DeviceState *dev, Error **errp)
 218{
 219    int idx = -1;
 220    X86CPU *cpu = X86_CPU(dev);
 221    X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
 222
 223    if (!x86ms->acpi_dev) {
 224        error_setg(errp, "CPU hot unplug not supported without ACPI");
 225        return;
 226    }
 227
 228    x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, &idx);
 229    assert(idx != -1);
 230    if (idx == 0) {
 231        error_setg(errp, "Boot CPU is unpluggable");
 232        return;
 233    }
 234
 235    hotplug_handler_unplug_request(x86ms->acpi_dev, dev,
 236                                   errp);
 237}
 238
 239void x86_cpu_unplug_cb(HotplugHandler *hotplug_dev,
 240                       DeviceState *dev, Error **errp)
 241{
 242    CPUArchId *found_cpu;
 243    Error *local_err = NULL;
 244    X86CPU *cpu = X86_CPU(dev);
 245    X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
 246
 247    hotplug_handler_unplug(x86ms->acpi_dev, dev, &local_err);
 248    if (local_err) {
 249        goto out;
 250    }
 251
 252    found_cpu = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, NULL);
 253    found_cpu->cpu = NULL;
 254    qdev_unrealize(dev);
 255
 256    /* decrement the number of CPUs */
 257    x86ms->boot_cpus--;
 258    /* Update the number of CPUs in CMOS */
 259    x86_rtc_set_cpus_count(x86ms->rtc, x86ms->boot_cpus);
 260    fw_cfg_modify_i16(x86ms->fw_cfg, FW_CFG_NB_CPUS, x86ms->boot_cpus);
 261 out:
 262    error_propagate(errp, local_err);
 263}
 264
 265void x86_cpu_pre_plug(HotplugHandler *hotplug_dev,
 266                      DeviceState *dev, Error **errp)
 267{
 268    int idx;
 269    CPUState *cs;
 270    CPUArchId *cpu_slot;
 271    X86CPUTopoIDs topo_ids;
 272    X86CPU *cpu = X86_CPU(dev);
 273    CPUX86State *env = &cpu->env;
 274    MachineState *ms = MACHINE(hotplug_dev);
 275    X86MachineState *x86ms = X86_MACHINE(hotplug_dev);
 276    unsigned int smp_cores = ms->smp.cores;
 277    unsigned int smp_threads = ms->smp.threads;
 278    X86CPUTopoInfo topo_info;
 279
 280    if (!object_dynamic_cast(OBJECT(cpu), ms->cpu_type)) {
 281        error_setg(errp, "Invalid CPU type, expected cpu type: '%s'",
 282                   ms->cpu_type);
 283        return;
 284    }
 285
 286    if (x86ms->acpi_dev) {
 287        Error *local_err = NULL;
 288
 289        hotplug_handler_pre_plug(HOTPLUG_HANDLER(x86ms->acpi_dev), dev,
 290                                 &local_err);
 291        if (local_err) {
 292            error_propagate(errp, local_err);
 293            return;
 294        }
 295    }
 296
 297    init_topo_info(&topo_info, x86ms);
 298
 299    env->nr_dies = ms->smp.dies;
 300
 301    /*
 302     * If APIC ID is not set,
 303     * set it based on socket/die/core/thread properties.
 304     */
 305    if (cpu->apic_id == UNASSIGNED_APIC_ID) {
 306        int max_socket = (ms->smp.max_cpus - 1) /
 307                                smp_threads / smp_cores / ms->smp.dies;
 308
 309        /*
 310         * die-id was optional in QEMU 4.0 and older, so keep it optional
 311         * if there's only one die per socket.
 312         */
 313        if (cpu->die_id < 0 && ms->smp.dies == 1) {
 314            cpu->die_id = 0;
 315        }
 316
 317        if (cpu->socket_id < 0) {
 318            error_setg(errp, "CPU socket-id is not set");
 319            return;
 320        } else if (cpu->socket_id > max_socket) {
 321            error_setg(errp, "Invalid CPU socket-id: %u must be in range 0:%u",
 322                       cpu->socket_id, max_socket);
 323            return;
 324        }
 325        if (cpu->die_id < 0) {
 326            error_setg(errp, "CPU die-id is not set");
 327            return;
 328        } else if (cpu->die_id > ms->smp.dies - 1) {
 329            error_setg(errp, "Invalid CPU die-id: %u must be in range 0:%u",
 330                       cpu->die_id, ms->smp.dies - 1);
 331            return;
 332        }
 333        if (cpu->core_id < 0) {
 334            error_setg(errp, "CPU core-id is not set");
 335            return;
 336        } else if (cpu->core_id > (smp_cores - 1)) {
 337            error_setg(errp, "Invalid CPU core-id: %u must be in range 0:%u",
 338                       cpu->core_id, smp_cores - 1);
 339            return;
 340        }
 341        if (cpu->thread_id < 0) {
 342            error_setg(errp, "CPU thread-id is not set");
 343            return;
 344        } else if (cpu->thread_id > (smp_threads - 1)) {
 345            error_setg(errp, "Invalid CPU thread-id: %u must be in range 0:%u",
 346                       cpu->thread_id, smp_threads - 1);
 347            return;
 348        }
 349
 350        topo_ids.pkg_id = cpu->socket_id;
 351        topo_ids.die_id = cpu->die_id;
 352        topo_ids.core_id = cpu->core_id;
 353        topo_ids.smt_id = cpu->thread_id;
 354        cpu->apic_id = x86_apicid_from_topo_ids(&topo_info, &topo_ids);
 355    }
 356
 357    cpu_slot = x86_find_cpu_slot(MACHINE(x86ms), cpu->apic_id, &idx);
 358    if (!cpu_slot) {
 359        MachineState *ms = MACHINE(x86ms);
 360
 361        x86_topo_ids_from_apicid(cpu->apic_id, &topo_info, &topo_ids);
 362        error_setg(errp,
 363            "Invalid CPU [socket: %u, die: %u, core: %u, thread: %u] with"
 364            " APIC ID %" PRIu32 ", valid index range 0:%d",
 365            topo_ids.pkg_id, topo_ids.die_id, topo_ids.core_id, topo_ids.smt_id,
 366            cpu->apic_id, ms->possible_cpus->len - 1);
 367        return;
 368    }
 369
 370    if (cpu_slot->cpu) {
 371        error_setg(errp, "CPU[%d] with APIC ID %" PRIu32 " exists",
 372                   idx, cpu->apic_id);
 373        return;
 374    }
 375
 376    /* if 'address' properties socket-id/core-id/thread-id are not set, set them
 377     * so that machine_query_hotpluggable_cpus would show correct values
 378     */
 379    /* TODO: move socket_id/core_id/thread_id checks into x86_cpu_realizefn()
 380     * once -smp refactoring is complete and there will be CPU private
 381     * CPUState::nr_cores and CPUState::nr_threads fields instead of globals */
 382    x86_topo_ids_from_apicid(cpu->apic_id, &topo_info, &topo_ids);
 383    if (cpu->socket_id != -1 && cpu->socket_id != topo_ids.pkg_id) {
 384        error_setg(errp, "property socket-id: %u doesn't match set apic-id:"
 385            " 0x%x (socket-id: %u)", cpu->socket_id, cpu->apic_id,
 386            topo_ids.pkg_id);
 387        return;
 388    }
 389    cpu->socket_id = topo_ids.pkg_id;
 390
 391    if (cpu->die_id != -1 && cpu->die_id != topo_ids.die_id) {
 392        error_setg(errp, "property die-id: %u doesn't match set apic-id:"
 393            " 0x%x (die-id: %u)", cpu->die_id, cpu->apic_id, topo_ids.die_id);
 394        return;
 395    }
 396    cpu->die_id = topo_ids.die_id;
 397
 398    if (cpu->core_id != -1 && cpu->core_id != topo_ids.core_id) {
 399        error_setg(errp, "property core-id: %u doesn't match set apic-id:"
 400            " 0x%x (core-id: %u)", cpu->core_id, cpu->apic_id,
 401            topo_ids.core_id);
 402        return;
 403    }
 404    cpu->core_id = topo_ids.core_id;
 405
 406    if (cpu->thread_id != -1 && cpu->thread_id != topo_ids.smt_id) {
 407        error_setg(errp, "property thread-id: %u doesn't match set apic-id:"
 408            " 0x%x (thread-id: %u)", cpu->thread_id, cpu->apic_id,
 409            topo_ids.smt_id);
 410        return;
 411    }
 412    cpu->thread_id = topo_ids.smt_id;
 413
 414    if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) &&
 415        !kvm_hv_vpindex_settable()) {
 416        error_setg(errp, "kernel doesn't allow setting HyperV VP_INDEX");
 417        return;
 418    }
 419
 420    cs = CPU(cpu);
 421    cs->cpu_index = idx;
 422
 423    numa_cpu_pre_plug(cpu_slot, dev, errp);
 424}
 425
 426CpuInstanceProperties
 427x86_cpu_index_to_props(MachineState *ms, unsigned cpu_index)
 428{
 429    MachineClass *mc = MACHINE_GET_CLASS(ms);
 430    const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
 431
 432    assert(cpu_index < possible_cpus->len);
 433    return possible_cpus->cpus[cpu_index].props;
 434}
 435
 436int64_t x86_get_default_cpu_node_id(const MachineState *ms, int idx)
 437{
 438   X86CPUTopoIDs topo_ids;
 439   X86MachineState *x86ms = X86_MACHINE(ms);
 440   X86CPUTopoInfo topo_info;
 441
 442   init_topo_info(&topo_info, x86ms);
 443
 444   assert(idx < ms->possible_cpus->len);
 445   x86_topo_ids_from_apicid(ms->possible_cpus->cpus[idx].arch_id,
 446                            &topo_info, &topo_ids);
 447   return topo_ids.pkg_id % ms->numa_state->num_nodes;
 448}
 449
 450const CPUArchIdList *x86_possible_cpu_arch_ids(MachineState *ms)
 451{
 452    X86MachineState *x86ms = X86_MACHINE(ms);
 453    unsigned int max_cpus = ms->smp.max_cpus;
 454    X86CPUTopoInfo topo_info;
 455    int i;
 456
 457    if (ms->possible_cpus) {
 458        /*
 459         * make sure that max_cpus hasn't changed since the first use, i.e.
 460         * -smp hasn't been parsed after it
 461         */
 462        assert(ms->possible_cpus->len == max_cpus);
 463        return ms->possible_cpus;
 464    }
 465
 466    ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
 467                                  sizeof(CPUArchId) * max_cpus);
 468    ms->possible_cpus->len = max_cpus;
 469
 470    init_topo_info(&topo_info, x86ms);
 471
 472    for (i = 0; i < ms->possible_cpus->len; i++) {
 473        X86CPUTopoIDs topo_ids;
 474
 475        ms->possible_cpus->cpus[i].type = ms->cpu_type;
 476        ms->possible_cpus->cpus[i].vcpus_count = 1;
 477        ms->possible_cpus->cpus[i].arch_id =
 478            x86_cpu_apic_id_from_index(x86ms, i);
 479        x86_topo_ids_from_apicid(ms->possible_cpus->cpus[i].arch_id,
 480                                 &topo_info, &topo_ids);
 481        ms->possible_cpus->cpus[i].props.has_socket_id = true;
 482        ms->possible_cpus->cpus[i].props.socket_id = topo_ids.pkg_id;
 483        if (ms->smp.dies > 1) {
 484            ms->possible_cpus->cpus[i].props.has_die_id = true;
 485            ms->possible_cpus->cpus[i].props.die_id = topo_ids.die_id;
 486        }
 487        ms->possible_cpus->cpus[i].props.has_core_id = true;
 488        ms->possible_cpus->cpus[i].props.core_id = topo_ids.core_id;
 489        ms->possible_cpus->cpus[i].props.has_thread_id = true;
 490        ms->possible_cpus->cpus[i].props.thread_id = topo_ids.smt_id;
 491    }
 492    return ms->possible_cpus;
 493}
 494
 495static void x86_nmi(NMIState *n, int cpu_index, Error **errp)
 496{
 497    /* cpu index isn't used */
 498    CPUState *cs;
 499
 500    CPU_FOREACH(cs) {
 501        X86CPU *cpu = X86_CPU(cs);
 502
 503        if (!cpu->apic_state) {
 504            cpu_interrupt(cs, CPU_INTERRUPT_NMI);
 505        } else {
 506            apic_deliver_nmi(cpu->apic_state);
 507        }
 508    }
 509}
 510
 511static long get_file_size(FILE *f)
 512{
 513    long where, size;
 514
 515    /* XXX: on Unix systems, using fstat() probably makes more sense */
 516
 517    where = ftell(f);
 518    fseek(f, 0, SEEK_END);
 519    size = ftell(f);
 520    fseek(f, where, SEEK_SET);
 521
 522    return size;
 523}
 524
 525/* TSC handling */
 526uint64_t cpu_get_tsc(CPUX86State *env)
 527{
 528    return cpus_get_elapsed_ticks();
 529}
 530
 531/* IRQ handling */
 532static void pic_irq_request(void *opaque, int irq, int level)
 533{
 534    CPUState *cs = first_cpu;
 535    X86CPU *cpu = X86_CPU(cs);
 536
 537    trace_x86_pic_interrupt(irq, level);
 538    if (cpu->apic_state && !kvm_irqchip_in_kernel() &&
 539        !whpx_apic_in_platform()) {
 540        CPU_FOREACH(cs) {
 541            cpu = X86_CPU(cs);
 542            if (apic_accept_pic_intr(cpu->apic_state)) {
 543                apic_deliver_pic_intr(cpu->apic_state, level);
 544            }
 545        }
 546    } else {
 547        if (level) {
 548            cpu_interrupt(cs, CPU_INTERRUPT_HARD);
 549        } else {
 550            cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
 551        }
 552    }
 553}
 554
 555qemu_irq x86_allocate_cpu_irq(void)
 556{
 557    return qemu_allocate_irq(pic_irq_request, NULL, 0);
 558}
 559
 560int cpu_get_pic_interrupt(CPUX86State *env)
 561{
 562    X86CPU *cpu = env_archcpu(env);
 563    int intno;
 564
 565    if (!kvm_irqchip_in_kernel() && !whpx_apic_in_platform()) {
 566        intno = apic_get_interrupt(cpu->apic_state);
 567        if (intno >= 0) {
 568            return intno;
 569        }
 570        /* read the irq from the PIC */
 571        if (!apic_accept_pic_intr(cpu->apic_state)) {
 572            return -1;
 573        }
 574    }
 575
 576    intno = pic_read_irq(isa_pic);
 577    return intno;
 578}
 579
 580DeviceState *cpu_get_current_apic(void)
 581{
 582    if (current_cpu) {
 583        X86CPU *cpu = X86_CPU(current_cpu);
 584        return cpu->apic_state;
 585    } else {
 586        return NULL;
 587    }
 588}
 589
 590void gsi_handler(void *opaque, int n, int level)
 591{
 592    GSIState *s = opaque;
 593
 594    trace_x86_gsi_interrupt(n, level);
 595    switch (n) {
 596    case 0 ... ISA_NUM_IRQS - 1:
 597        if (s->i8259_irq[n]) {
 598            /* Under KVM, Kernel will forward to both PIC and IOAPIC */
 599            qemu_set_irq(s->i8259_irq[n], level);
 600        }
 601        /* fall through */
 602    case ISA_NUM_IRQS ... IOAPIC_NUM_PINS - 1:
 603        qemu_set_irq(s->ioapic_irq[n], level);
 604        break;
 605    case IO_APIC_SECONDARY_IRQBASE
 606        ... IO_APIC_SECONDARY_IRQBASE + IOAPIC_NUM_PINS - 1:
 607        qemu_set_irq(s->ioapic2_irq[n - IO_APIC_SECONDARY_IRQBASE], level);
 608        break;
 609    }
 610}
 611
 612void ioapic_init_gsi(GSIState *gsi_state, const char *parent_name)
 613{
 614    DeviceState *dev;
 615    SysBusDevice *d;
 616    unsigned int i;
 617
 618    assert(parent_name);
 619    if (kvm_ioapic_in_kernel()) {
 620        dev = qdev_new(TYPE_KVM_IOAPIC);
 621    } else {
 622        dev = qdev_new(TYPE_IOAPIC);
 623    }
 624    object_property_add_child(object_resolve_path(parent_name, NULL),
 625                              "ioapic", OBJECT(dev));
 626    d = SYS_BUS_DEVICE(dev);
 627    sysbus_realize_and_unref(d, &error_fatal);
 628    sysbus_mmio_map(d, 0, IO_APIC_DEFAULT_ADDRESS);
 629
 630    for (i = 0; i < IOAPIC_NUM_PINS; i++) {
 631        gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i);
 632    }
 633}
 634
 635DeviceState *ioapic_init_secondary(GSIState *gsi_state)
 636{
 637    DeviceState *dev;
 638    SysBusDevice *d;
 639    unsigned int i;
 640
 641    dev = qdev_new(TYPE_IOAPIC);
 642    d = SYS_BUS_DEVICE(dev);
 643    sysbus_realize_and_unref(d, &error_fatal);
 644    sysbus_mmio_map(d, 0, IO_APIC_SECONDARY_ADDRESS);
 645
 646    for (i = 0; i < IOAPIC_NUM_PINS; i++) {
 647        gsi_state->ioapic2_irq[i] = qdev_get_gpio_in(dev, i);
 648    }
 649    return dev;
 650}
 651
 652struct setup_data {
 653    uint64_t next;
 654    uint32_t type;
 655    uint32_t len;
 656    uint8_t data[];
 657} __attribute__((packed));
 658
 659
 660/*
 661 * The entry point into the kernel for PVH boot is different from
 662 * the native entry point.  The PVH entry is defined by the x86/HVM
 663 * direct boot ABI and is available in an ELFNOTE in the kernel binary.
 664 *
 665 * This function is passed to load_elf() when it is called from
 666 * load_elfboot() which then additionally checks for an ELF Note of
 667 * type XEN_ELFNOTE_PHYS32_ENTRY and passes it to this function to
 668 * parse the PVH entry address from the ELF Note.
 669 *
 670 * Due to trickery in elf_opts.h, load_elf() is actually available as
 671 * load_elf32() or load_elf64() and this routine needs to be able
 672 * to deal with being called as 32 or 64 bit.
 673 *
 674 * The address of the PVH entry point is saved to the 'pvh_start_addr'
 675 * global variable.  (although the entry point is 32-bit, the kernel
 676 * binary can be either 32-bit or 64-bit).
 677 */
 678static uint64_t read_pvh_start_addr(void *arg1, void *arg2, bool is64)
 679{
 680    size_t *elf_note_data_addr;
 681
 682    /* Check if ELF Note header passed in is valid */
 683    if (arg1 == NULL) {
 684        return 0;
 685    }
 686
 687    if (is64) {
 688        struct elf64_note *nhdr64 = (struct elf64_note *)arg1;
 689        uint64_t nhdr_size64 = sizeof(struct elf64_note);
 690        uint64_t phdr_align = *(uint64_t *)arg2;
 691        uint64_t nhdr_namesz = nhdr64->n_namesz;
 692
 693        elf_note_data_addr =
 694            ((void *)nhdr64) + nhdr_size64 +
 695            QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
 696
 697        pvh_start_addr = *elf_note_data_addr;
 698    } else {
 699        struct elf32_note *nhdr32 = (struct elf32_note *)arg1;
 700        uint32_t nhdr_size32 = sizeof(struct elf32_note);
 701        uint32_t phdr_align = *(uint32_t *)arg2;
 702        uint32_t nhdr_namesz = nhdr32->n_namesz;
 703
 704        elf_note_data_addr =
 705            ((void *)nhdr32) + nhdr_size32 +
 706            QEMU_ALIGN_UP(nhdr_namesz, phdr_align);
 707
 708        pvh_start_addr = *(uint32_t *)elf_note_data_addr;
 709    }
 710
 711    return pvh_start_addr;
 712}
 713
 714static bool load_elfboot(const char *kernel_filename,
 715                         int kernel_file_size,
 716                         uint8_t *header,
 717                         size_t pvh_xen_start_addr,
 718                         FWCfgState *fw_cfg)
 719{
 720    uint32_t flags = 0;
 721    uint32_t mh_load_addr = 0;
 722    uint32_t elf_kernel_size = 0;
 723    uint64_t elf_entry;
 724    uint64_t elf_low, elf_high;
 725    int kernel_size;
 726
 727    if (ldl_p(header) != 0x464c457f) {
 728        return false; /* no elfboot */
 729    }
 730
 731    bool elf_is64 = header[EI_CLASS] == ELFCLASS64;
 732    flags = elf_is64 ?
 733        ((Elf64_Ehdr *)header)->e_flags : ((Elf32_Ehdr *)header)->e_flags;
 734
 735    if (flags & 0x00010004) { /* LOAD_ELF_HEADER_HAS_ADDR */
 736        error_report("elfboot unsupported flags = %x", flags);
 737        exit(1);
 738    }
 739
 740    uint64_t elf_note_type = XEN_ELFNOTE_PHYS32_ENTRY;
 741    kernel_size = load_elf(kernel_filename, read_pvh_start_addr,
 742                           NULL, &elf_note_type, &elf_entry,
 743                           &elf_low, &elf_high, NULL, 0, I386_ELF_MACHINE,
 744                           0, 0);
 745
 746    if (kernel_size < 0) {
 747        error_report("Error while loading elf kernel");
 748        exit(1);
 749    }
 750    mh_load_addr = elf_low;
 751    elf_kernel_size = elf_high - elf_low;
 752
 753    if (pvh_start_addr == 0) {
 754        error_report("Error loading uncompressed kernel without PVH ELF Note");
 755        exit(1);
 756    }
 757    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr);
 758    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
 759    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, elf_kernel_size);
 760
 761    return true;
 762}
 763
 764void x86_load_linux(X86MachineState *x86ms,
 765                    FWCfgState *fw_cfg,
 766                    int acpi_data_size,
 767                    bool pvh_enabled)
 768{
 769    bool linuxboot_dma_enabled = X86_MACHINE_GET_CLASS(x86ms)->fwcfg_dma_enabled;
 770    uint16_t protocol;
 771    int setup_size, kernel_size, cmdline_size;
 772    int dtb_size, setup_data_offset;
 773    uint32_t initrd_max;
 774    uint8_t header[8192], *setup, *kernel;
 775    hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
 776    FILE *f;
 777    char *vmode;
 778    MachineState *machine = MACHINE(x86ms);
 779    struct setup_data *setup_data;
 780    const char *kernel_filename = machine->kernel_filename;
 781    const char *initrd_filename = machine->initrd_filename;
 782    const char *dtb_filename = machine->dtb;
 783    const char *kernel_cmdline = machine->kernel_cmdline;
 784    SevKernelLoaderContext sev_load_ctx = {};
 785
 786    /* Align to 16 bytes as a paranoia measure */
 787    cmdline_size = (strlen(kernel_cmdline) + 16) & ~15;
 788
 789    /* load the kernel header */
 790    f = fopen(kernel_filename, "rb");
 791    if (!f) {
 792        fprintf(stderr, "qemu: could not open kernel file '%s': %s\n",
 793                kernel_filename, strerror(errno));
 794        exit(1);
 795    }
 796
 797    kernel_size = get_file_size(f);
 798    if (!kernel_size ||
 799        fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=
 800        MIN(ARRAY_SIZE(header), kernel_size)) {
 801        fprintf(stderr, "qemu: could not load kernel '%s': %s\n",
 802                kernel_filename, strerror(errno));
 803        exit(1);
 804    }
 805
 806    /* kernel protocol version */
 807    if (ldl_p(header + 0x202) == 0x53726448) {
 808        protocol = lduw_p(header + 0x206);
 809    } else {
 810        /*
 811         * This could be a multiboot kernel. If it is, let's stop treating it
 812         * like a Linux kernel.
 813         * Note: some multiboot images could be in the ELF format (the same of
 814         * PVH), so we try multiboot first since we check the multiboot magic
 815         * header before to load it.
 816         */
 817        if (load_multiboot(x86ms, fw_cfg, f, kernel_filename, initrd_filename,
 818                           kernel_cmdline, kernel_size, header)) {
 819            return;
 820        }
 821        /*
 822         * Check if the file is an uncompressed kernel file (ELF) and load it,
 823         * saving the PVH entry point used by the x86/HVM direct boot ABI.
 824         * If load_elfboot() is successful, populate the fw_cfg info.
 825         */
 826        if (pvh_enabled &&
 827            load_elfboot(kernel_filename, kernel_size,
 828                         header, pvh_start_addr, fw_cfg)) {
 829            fclose(f);
 830
 831            fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
 832                strlen(kernel_cmdline) + 1);
 833            fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
 834
 835            fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, sizeof(header));
 836            fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA,
 837                             header, sizeof(header));
 838
 839            /* load initrd */
 840            if (initrd_filename) {
 841                GMappedFile *mapped_file;
 842                gsize initrd_size;
 843                gchar *initrd_data;
 844                GError *gerr = NULL;
 845
 846                mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
 847                if (!mapped_file) {
 848                    fprintf(stderr, "qemu: error reading initrd %s: %s\n",
 849                            initrd_filename, gerr->message);
 850                    exit(1);
 851                }
 852                x86ms->initrd_mapped_file = mapped_file;
 853
 854                initrd_data = g_mapped_file_get_contents(mapped_file);
 855                initrd_size = g_mapped_file_get_length(mapped_file);
 856                initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
 857                if (initrd_size >= initrd_max) {
 858                    fprintf(stderr, "qemu: initrd is too large, cannot support."
 859                            "(max: %"PRIu32", need %"PRId64")\n",
 860                            initrd_max, (uint64_t)initrd_size);
 861                    exit(1);
 862                }
 863
 864                initrd_addr = (initrd_max - initrd_size) & ~4095;
 865
 866                fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
 867                fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
 868                fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data,
 869                                 initrd_size);
 870            }
 871
 872            option_rom[nb_option_roms].bootindex = 0;
 873            option_rom[nb_option_roms].name = "pvh.bin";
 874            nb_option_roms++;
 875
 876            return;
 877        }
 878        protocol = 0;
 879    }
 880
 881    if (protocol < 0x200 || !(header[0x211] & 0x01)) {
 882        /* Low kernel */
 883        real_addr    = 0x90000;
 884        cmdline_addr = 0x9a000 - cmdline_size;
 885        prot_addr    = 0x10000;
 886    } else if (protocol < 0x202) {
 887        /* High but ancient kernel */
 888        real_addr    = 0x90000;
 889        cmdline_addr = 0x9a000 - cmdline_size;
 890        prot_addr    = 0x100000;
 891    } else {
 892        /* High and recent kernel */
 893        real_addr    = 0x10000;
 894        cmdline_addr = 0x20000;
 895        prot_addr    = 0x100000;
 896    }
 897
 898    /* highest address for loading the initrd */
 899    if (protocol >= 0x20c &&
 900        lduw_p(header + 0x236) & XLF_CAN_BE_LOADED_ABOVE_4G) {
 901        /*
 902         * Linux has supported initrd up to 4 GB for a very long time (2007,
 903         * long before XLF_CAN_BE_LOADED_ABOVE_4G which was added in 2013),
 904         * though it only sets initrd_max to 2 GB to "work around bootloader
 905         * bugs". Luckily, QEMU firmware(which does something like bootloader)
 906         * has supported this.
 907         *
 908         * It's believed that if XLF_CAN_BE_LOADED_ABOVE_4G is set, initrd can
 909         * be loaded into any address.
 910         *
 911         * In addition, initrd_max is uint32_t simply because QEMU doesn't
 912         * support the 64-bit boot protocol (specifically the ext_ramdisk_image
 913         * field).
 914         *
 915         * Therefore here just limit initrd_max to UINT32_MAX simply as well.
 916         */
 917        initrd_max = UINT32_MAX;
 918    } else if (protocol >= 0x203) {
 919        initrd_max = ldl_p(header + 0x22c);
 920    } else {
 921        initrd_max = 0x37ffffff;
 922    }
 923
 924    if (initrd_max >= x86ms->below_4g_mem_size - acpi_data_size) {
 925        initrd_max = x86ms->below_4g_mem_size - acpi_data_size - 1;
 926    }
 927
 928    fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);
 929    fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline) + 1);
 930    fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, kernel_cmdline);
 931    sev_load_ctx.cmdline_data = (char *)kernel_cmdline;
 932    sev_load_ctx.cmdline_size = strlen(kernel_cmdline) + 1;
 933
 934    if (protocol >= 0x202) {
 935        stl_p(header + 0x228, cmdline_addr);
 936    } else {
 937        stw_p(header + 0x20, 0xA33F);
 938        stw_p(header + 0x22, cmdline_addr - real_addr);
 939    }
 940
 941    /* handle vga= parameter */
 942    vmode = strstr(kernel_cmdline, "vga=");
 943    if (vmode) {
 944        unsigned int video_mode;
 945        const char *end;
 946        int ret;
 947        /* skip "vga=" */
 948        vmode += 4;
 949        if (!strncmp(vmode, "normal", 6)) {
 950            video_mode = 0xffff;
 951        } else if (!strncmp(vmode, "ext", 3)) {
 952            video_mode = 0xfffe;
 953        } else if (!strncmp(vmode, "ask", 3)) {
 954            video_mode = 0xfffd;
 955        } else {
 956            ret = qemu_strtoui(vmode, &end, 0, &video_mode);
 957            if (ret != 0 || (*end && *end != ' ')) {
 958                fprintf(stderr, "qemu: invalid 'vga=' kernel parameter.\n");
 959                exit(1);
 960            }
 961        }
 962        stw_p(header + 0x1fa, video_mode);
 963    }
 964
 965    /* loader type */
 966    /*
 967     * High nybble = B reserved for QEMU; low nybble is revision number.
 968     * If this code is substantially changed, you may want to consider
 969     * incrementing the revision.
 970     */
 971    if (protocol >= 0x200) {
 972        header[0x210] = 0xB0;
 973    }
 974    /* heap */
 975    if (protocol >= 0x201) {
 976        header[0x211] |= 0x80; /* CAN_USE_HEAP */
 977        stw_p(header + 0x224, cmdline_addr - real_addr - 0x200);
 978    }
 979
 980    /* load initrd */
 981    if (initrd_filename) {
 982        GMappedFile *mapped_file;
 983        gsize initrd_size;
 984        gchar *initrd_data;
 985        GError *gerr = NULL;
 986
 987        if (protocol < 0x200) {
 988            fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");
 989            exit(1);
 990        }
 991
 992        mapped_file = g_mapped_file_new(initrd_filename, false, &gerr);
 993        if (!mapped_file) {
 994            fprintf(stderr, "qemu: error reading initrd %s: %s\n",
 995                    initrd_filename, gerr->message);
 996            exit(1);
 997        }
 998        x86ms->initrd_mapped_file = mapped_file;
 999
1000        initrd_data = g_mapped_file_get_contents(mapped_file);
1001        initrd_size = g_mapped_file_get_length(mapped_file);
1002        if (initrd_size >= initrd_max) {
1003            fprintf(stderr, "qemu: initrd is too large, cannot support."
1004                    "(max: %"PRIu32", need %"PRId64")\n",
1005                    initrd_max, (uint64_t)initrd_size);
1006            exit(1);
1007        }
1008
1009        initrd_addr = (initrd_max - initrd_size) & ~4095;
1010
1011        fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
1012        fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
1013        fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);
1014        sev_load_ctx.initrd_data = initrd_data;
1015        sev_load_ctx.initrd_size = initrd_size;
1016
1017        stl_p(header + 0x218, initrd_addr);
1018        stl_p(header + 0x21c, initrd_size);
1019    }
1020
1021    /* load kernel and setup */
1022    setup_size = header[0x1f1];
1023    if (setup_size == 0) {
1024        setup_size = 4;
1025    }
1026    setup_size = (setup_size + 1) * 512;
1027    if (setup_size > kernel_size) {
1028        fprintf(stderr, "qemu: invalid kernel header\n");
1029        exit(1);
1030    }
1031    kernel_size -= setup_size;
1032
1033    setup  = g_malloc(setup_size);
1034    kernel = g_malloc(kernel_size);
1035    fseek(f, 0, SEEK_SET);
1036    if (fread(setup, 1, setup_size, f) != setup_size) {
1037        fprintf(stderr, "fread() failed\n");
1038        exit(1);
1039    }
1040    if (fread(kernel, 1, kernel_size, f) != kernel_size) {
1041        fprintf(stderr, "fread() failed\n");
1042        exit(1);
1043    }
1044    fclose(f);
1045
1046    /* append dtb to kernel */
1047    if (dtb_filename) {
1048        if (protocol < 0x209) {
1049            fprintf(stderr, "qemu: Linux kernel too old to load a dtb\n");
1050            exit(1);
1051        }
1052
1053        dtb_size = get_image_size(dtb_filename);
1054        if (dtb_size <= 0) {
1055            fprintf(stderr, "qemu: error reading dtb %s: %s\n",
1056                    dtb_filename, strerror(errno));
1057            exit(1);
1058        }
1059
1060        setup_data_offset = QEMU_ALIGN_UP(kernel_size, 16);
1061        kernel_size = setup_data_offset + sizeof(struct setup_data) + dtb_size;
1062        kernel = g_realloc(kernel, kernel_size);
1063
1064        stq_p(header + 0x250, prot_addr + setup_data_offset);
1065
1066        setup_data = (struct setup_data *)(kernel + setup_data_offset);
1067        setup_data->next = 0;
1068        setup_data->type = cpu_to_le32(SETUP_DTB);
1069        setup_data->len = cpu_to_le32(dtb_size);
1070
1071        load_image_size(dtb_filename, setup_data->data, dtb_size);
1072    }
1073
1074    /*
1075     * If we're starting an encrypted VM, it will be OVMF based, which uses the
1076     * efi stub for booting and doesn't require any values to be placed in the
1077     * kernel header.  We therefore don't update the header so the hash of the
1078     * kernel on the other side of the fw_cfg interface matches the hash of the
1079     * file the user passed in.
1080     */
1081    if (!sev_enabled()) {
1082        memcpy(setup, header, MIN(sizeof(header), setup_size));
1083    }
1084
1085    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);
1086    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);
1087    fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA, kernel, kernel_size);
1088    sev_load_ctx.kernel_data = (char *)kernel;
1089    sev_load_ctx.kernel_size = kernel_size;
1090
1091    fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);
1092    fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);
1093    fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);
1094    sev_load_ctx.setup_data = (char *)setup;
1095    sev_load_ctx.setup_size = setup_size;
1096
1097    if (sev_enabled()) {
1098        sev_add_kernel_loader_hashes(&sev_load_ctx, &error_fatal);
1099    }
1100
1101    option_rom[nb_option_roms].bootindex = 0;
1102    option_rom[nb_option_roms].name = "linuxboot.bin";
1103    if (linuxboot_dma_enabled && fw_cfg_dma_enabled(fw_cfg)) {
1104        option_rom[nb_option_roms].name = "linuxboot_dma.bin";
1105    }
1106    nb_option_roms++;
1107}
1108
1109void x86_bios_rom_init(MachineState *ms, const char *default_firmware,
1110                       MemoryRegion *rom_memory, bool isapc_ram_fw)
1111{
1112    const char *bios_name;
1113    char *filename;
1114    MemoryRegion *bios, *isa_bios;
1115    int bios_size, isa_bios_size;
1116    int ret;
1117
1118    /* BIOS load */
1119    bios_name = ms->firmware ?: default_firmware;
1120    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
1121    if (filename) {
1122        bios_size = get_image_size(filename);
1123    } else {
1124        bios_size = -1;
1125    }
1126    if (bios_size <= 0 ||
1127        (bios_size % 65536) != 0) {
1128        goto bios_error;
1129    }
1130    bios = g_malloc(sizeof(*bios));
1131    memory_region_init_ram(bios, NULL, "pc.bios", bios_size, &error_fatal);
1132    if (!isapc_ram_fw) {
1133        memory_region_set_readonly(bios, true);
1134    }
1135    ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size), -1);
1136    if (ret != 0) {
1137    bios_error:
1138        fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);
1139        exit(1);
1140    }
1141    g_free(filename);
1142
1143    /* map the last 128KB of the BIOS in ISA space */
1144    isa_bios_size = MIN(bios_size, 128 * KiB);
1145    isa_bios = g_malloc(sizeof(*isa_bios));
1146    memory_region_init_alias(isa_bios, NULL, "isa-bios", bios,
1147                             bios_size - isa_bios_size, isa_bios_size);
1148    memory_region_add_subregion_overlap(rom_memory,
1149                                        0x100000 - isa_bios_size,
1150                                        isa_bios,
1151                                        1);
1152    if (!isapc_ram_fw) {
1153        memory_region_set_readonly(isa_bios, true);
1154    }
1155
1156    /* map all the bios at the top of memory */
1157    memory_region_add_subregion(rom_memory,
1158                                (uint32_t)(-bios_size),
1159                                bios);
1160}
1161
1162bool x86_machine_is_smm_enabled(const X86MachineState *x86ms)
1163{
1164    bool smm_available = false;
1165
1166    if (x86ms->smm == ON_OFF_AUTO_OFF) {
1167        return false;
1168    }
1169
1170    if (tcg_enabled() || qtest_enabled()) {
1171        smm_available = true;
1172    } else if (kvm_enabled()) {
1173        smm_available = kvm_has_smm();
1174    }
1175
1176    if (smm_available) {
1177        return true;
1178    }
1179
1180    if (x86ms->smm == ON_OFF_AUTO_ON) {
1181        error_report("System Management Mode not supported by this hypervisor.");
1182        exit(1);
1183    }
1184    return false;
1185}
1186
1187static void x86_machine_get_smm(Object *obj, Visitor *v, const char *name,
1188                               void *opaque, Error **errp)
1189{
1190    X86MachineState *x86ms = X86_MACHINE(obj);
1191    OnOffAuto smm = x86ms->smm;
1192
1193    visit_type_OnOffAuto(v, name, &smm, errp);
1194}
1195
1196static void x86_machine_set_smm(Object *obj, Visitor *v, const char *name,
1197                               void *opaque, Error **errp)
1198{
1199    X86MachineState *x86ms = X86_MACHINE(obj);
1200
1201    visit_type_OnOffAuto(v, name, &x86ms->smm, errp);
1202}
1203
1204bool x86_machine_is_acpi_enabled(const X86MachineState *x86ms)
1205{
1206    if (x86ms->acpi == ON_OFF_AUTO_OFF) {
1207        return false;
1208    }
1209    return true;
1210}
1211
1212static void x86_machine_get_acpi(Object *obj, Visitor *v, const char *name,
1213                                 void *opaque, Error **errp)
1214{
1215    X86MachineState *x86ms = X86_MACHINE(obj);
1216    OnOffAuto acpi = x86ms->acpi;
1217
1218    visit_type_OnOffAuto(v, name, &acpi, errp);
1219}
1220
1221static void x86_machine_set_acpi(Object *obj, Visitor *v, const char *name,
1222                                 void *opaque, Error **errp)
1223{
1224    X86MachineState *x86ms = X86_MACHINE(obj);
1225
1226    visit_type_OnOffAuto(v, name, &x86ms->acpi, errp);
1227}
1228
1229static char *x86_machine_get_oem_id(Object *obj, Error **errp)
1230{
1231    X86MachineState *x86ms = X86_MACHINE(obj);
1232
1233    return g_strdup(x86ms->oem_id);
1234}
1235
1236static void x86_machine_set_oem_id(Object *obj, const char *value, Error **errp)
1237{
1238    X86MachineState *x86ms = X86_MACHINE(obj);
1239    size_t len = strlen(value);
1240
1241    if (len > 6) {
1242        error_setg(errp,
1243                   "User specified "X86_MACHINE_OEM_ID" value is bigger than "
1244                   "6 bytes in size");
1245        return;
1246    }
1247
1248    strncpy(x86ms->oem_id, value, 6);
1249}
1250
1251static char *x86_machine_get_oem_table_id(Object *obj, Error **errp)
1252{
1253    X86MachineState *x86ms = X86_MACHINE(obj);
1254
1255    return g_strdup(x86ms->oem_table_id);
1256}
1257
1258static void x86_machine_set_oem_table_id(Object *obj, const char *value,
1259                                         Error **errp)
1260{
1261    X86MachineState *x86ms = X86_MACHINE(obj);
1262    size_t len = strlen(value);
1263
1264    if (len > 8) {
1265        error_setg(errp,
1266                   "User specified "X86_MACHINE_OEM_TABLE_ID
1267                   " value is bigger than "
1268                   "8 bytes in size");
1269        return;
1270    }
1271    strncpy(x86ms->oem_table_id, value, 8);
1272}
1273
1274static void x86_machine_get_bus_lock_ratelimit(Object *obj, Visitor *v,
1275                                const char *name, void *opaque, Error **errp)
1276{
1277    X86MachineState *x86ms = X86_MACHINE(obj);
1278    uint64_t bus_lock_ratelimit = x86ms->bus_lock_ratelimit;
1279
1280    visit_type_uint64(v, name, &bus_lock_ratelimit, errp);
1281}
1282
1283static void x86_machine_set_bus_lock_ratelimit(Object *obj, Visitor *v,
1284                               const char *name, void *opaque, Error **errp)
1285{
1286    X86MachineState *x86ms = X86_MACHINE(obj);
1287
1288    visit_type_uint64(v, name, &x86ms->bus_lock_ratelimit, errp);
1289}
1290
1291static void machine_get_sgx_epc(Object *obj, Visitor *v, const char *name,
1292                                void *opaque, Error **errp)
1293{
1294    X86MachineState *x86ms = X86_MACHINE(obj);
1295    SgxEPCList *list = x86ms->sgx_epc_list;
1296
1297    visit_type_SgxEPCList(v, name, &list, errp);
1298}
1299
1300static void machine_set_sgx_epc(Object *obj, Visitor *v, const char *name,
1301                                void *opaque, Error **errp)
1302{
1303    X86MachineState *x86ms = X86_MACHINE(obj);
1304    SgxEPCList *list;
1305
1306    list = x86ms->sgx_epc_list;
1307    visit_type_SgxEPCList(v, name, &x86ms->sgx_epc_list, errp);
1308
1309    qapi_free_SgxEPCList(list);
1310}
1311
1312static void x86_machine_initfn(Object *obj)
1313{
1314    X86MachineState *x86ms = X86_MACHINE(obj);
1315
1316    x86ms->smm = ON_OFF_AUTO_AUTO;
1317    x86ms->acpi = ON_OFF_AUTO_AUTO;
1318    x86ms->pci_irq_mask = ACPI_BUILD_PCI_IRQS;
1319    x86ms->oem_id = g_strndup(ACPI_BUILD_APPNAME6, 6);
1320    x86ms->oem_table_id = g_strndup(ACPI_BUILD_APPNAME8, 8);
1321    x86ms->bus_lock_ratelimit = 0;
1322}
1323
1324static void x86_machine_class_init(ObjectClass *oc, void *data)
1325{
1326    MachineClass *mc = MACHINE_CLASS(oc);
1327    X86MachineClass *x86mc = X86_MACHINE_CLASS(oc);
1328    NMIClass *nc = NMI_CLASS(oc);
1329
1330    mc->cpu_index_to_instance_props = x86_cpu_index_to_props;
1331    mc->get_default_cpu_node_id = x86_get_default_cpu_node_id;
1332    mc->possible_cpu_arch_ids = x86_possible_cpu_arch_ids;
1333    x86mc->compat_apic_id_mode = false;
1334    x86mc->save_tsc_khz = true;
1335    x86mc->fwcfg_dma_enabled = true;
1336    nc->nmi_monitor_handler = x86_nmi;
1337
1338    object_class_property_add(oc, X86_MACHINE_SMM, "OnOffAuto",
1339        x86_machine_get_smm, x86_machine_set_smm,
1340        NULL, NULL);
1341    object_class_property_set_description(oc, X86_MACHINE_SMM,
1342        "Enable SMM");
1343
1344    object_class_property_add(oc, X86_MACHINE_ACPI, "OnOffAuto",
1345        x86_machine_get_acpi, x86_machine_set_acpi,
1346        NULL, NULL);
1347    object_class_property_set_description(oc, X86_MACHINE_ACPI,
1348        "Enable ACPI");
1349
1350    object_class_property_add_str(oc, X86_MACHINE_OEM_ID,
1351                                  x86_machine_get_oem_id,
1352                                  x86_machine_set_oem_id);
1353    object_class_property_set_description(oc, X86_MACHINE_OEM_ID,
1354                                          "Override the default value of field OEMID "
1355                                          "in ACPI table header."
1356                                          "The string may be up to 6 bytes in size");
1357
1358
1359    object_class_property_add_str(oc, X86_MACHINE_OEM_TABLE_ID,
1360                                  x86_machine_get_oem_table_id,
1361                                  x86_machine_set_oem_table_id);
1362    object_class_property_set_description(oc, X86_MACHINE_OEM_TABLE_ID,
1363                                          "Override the default value of field OEM Table ID "
1364                                          "in ACPI table header."
1365                                          "The string may be up to 8 bytes in size");
1366
1367    object_class_property_add(oc, X86_MACHINE_BUS_LOCK_RATELIMIT, "uint64_t",
1368                                x86_machine_get_bus_lock_ratelimit,
1369                                x86_machine_set_bus_lock_ratelimit, NULL, NULL);
1370    object_class_property_set_description(oc, X86_MACHINE_BUS_LOCK_RATELIMIT,
1371            "Set the ratelimit for the bus locks acquired in VMs");
1372
1373    object_class_property_add(oc, "sgx-epc", "SgxEPC",
1374        machine_get_sgx_epc, machine_set_sgx_epc,
1375        NULL, NULL);
1376    object_class_property_set_description(oc, "sgx-epc",
1377        "SGX EPC device");
1378}
1379
1380static const TypeInfo x86_machine_info = {
1381    .name = TYPE_X86_MACHINE,
1382    .parent = TYPE_MACHINE,
1383    .abstract = true,
1384    .instance_size = sizeof(X86MachineState),
1385    .instance_init = x86_machine_initfn,
1386    .class_size = sizeof(X86MachineClass),
1387    .class_init = x86_machine_class_init,
1388    .interfaces = (InterfaceInfo[]) {
1389         { TYPE_NMI },
1390         { }
1391    },
1392};
1393
1394static void x86_machine_register_types(void)
1395{
1396    type_register_static(&x86_machine_info);
1397}
1398
1399type_init(x86_machine_register_types)
1400