qemu/hw/i386/acpi-build.c
<<
>>
Prefs
   1/* Support for generating ACPI tables and passing them to Guests
   2 *
   3 * Copyright (C) 2008-2010  Kevin O'Connor <kevin@koconnor.net>
   4 * Copyright (C) 2006 Fabrice Bellard
   5 * Copyright (C) 2013 Red Hat Inc
   6 *
   7 * Author: Michael S. Tsirkin <mst@redhat.com>
   8 *
   9 * This program is free software; you can redistribute it and/or modify
  10 * it under the terms of the GNU General Public License as published by
  11 * the Free Software Foundation; either version 2 of the License, or
  12 * (at your option) any later version.
  13
  14 * This program is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17 * GNU General Public License for more details.
  18
  19 * You should have received a copy of the GNU General Public License along
  20 * with this program; if not, see <http://www.gnu.org/licenses/>.
  21 */
  22
  23#include "qemu/osdep.h"
  24#include "qapi/error.h"
  25#include "acpi-build.h"
  26#include "qemu-common.h"
  27#include "qemu/bitmap.h"
  28#include "qemu/error-report.h"
  29#include "hw/pci/pci.h"
  30#include "qom/cpu.h"
  31#include "hw/i386/pc.h"
  32#include "target/i386/cpu.h"
  33#include "hw/timer/hpet.h"
  34#include "hw/acpi/acpi-defs.h"
  35#include "hw/acpi/acpi.h"
  36#include "hw/acpi/cpu.h"
  37#include "hw/nvram/fw_cfg.h"
  38#include "hw/acpi/bios-linker-loader.h"
  39#include "hw/loader.h"
  40#include "hw/isa/isa.h"
  41#include "hw/block/fdc.h"
  42#include "hw/acpi/memory_hotplug.h"
  43#include "sysemu/tpm.h"
  44#include "hw/acpi/tpm.h"
  45#include "hw/acpi/vmgenid.h"
  46#include "sysemu/tpm_backend.h"
  47#include "hw/timer/mc146818rtc_regs.h"
  48#include "sysemu/numa.h"
  49
  50/* Supported chipsets: */
  51#include "hw/acpi/piix4.h"
  52#include "hw/acpi/pcihp.h"
  53#include "hw/i386/ich9.h"
  54#include "hw/pci/pci_bus.h"
  55#include "hw/pci-host/q35.h"
  56#include "hw/i386/x86-iommu.h"
  57
  58#include "hw/acpi/aml-build.h"
  59
  60#include "qom/qom-qobject.h"
  61#include "hw/i386/amd_iommu.h"
  62#include "hw/i386/intel_iommu.h"
  63
  64#include "hw/acpi/ipmi.h"
  65
  66/* These are used to size the ACPI tables for -M pc-i440fx-1.7 and
  67 * -M pc-i440fx-2.0.  Even if the actual amount of AML generated grows
  68 * a little bit, there should be plenty of free space since the DSDT
  69 * shrunk by ~1.5k between QEMU 2.0 and QEMU 2.1.
  70 */
  71#define ACPI_BUILD_LEGACY_CPU_AML_SIZE    97
  72#define ACPI_BUILD_ALIGN_SIZE             0x1000
  73
  74#define ACPI_BUILD_TABLE_SIZE             0x20000
  75
  76/* #define DEBUG_ACPI_BUILD */
  77#ifdef DEBUG_ACPI_BUILD
  78#define ACPI_BUILD_DPRINTF(fmt, ...)        \
  79    do {printf("ACPI_BUILD: " fmt, ## __VA_ARGS__); } while (0)
  80#else
  81#define ACPI_BUILD_DPRINTF(fmt, ...)
  82#endif
  83
  84/* Default IOAPIC ID */
  85#define ACPI_BUILD_IOAPIC_ID 0x0
  86
  87typedef struct AcpiMcfgInfo {
  88    uint64_t mcfg_base;
  89    uint32_t mcfg_size;
  90} AcpiMcfgInfo;
  91
  92typedef struct AcpiPmInfo {
  93    bool force_rev1_fadt;
  94    bool s3_disabled;
  95    bool s4_disabled;
  96    bool pcihp_bridge_en;
  97    uint8_t s4_val;
  98    uint16_t sci_int;
  99    uint8_t acpi_enable_cmd;
 100    uint8_t acpi_disable_cmd;
 101    uint32_t gpe0_blk;
 102    uint32_t gpe0_blk_len;
 103    uint32_t io_base;
 104    uint16_t cpu_hp_io_base;
 105    uint16_t pcihp_io_base;
 106    uint16_t pcihp_io_len;
 107} AcpiPmInfo;
 108
 109typedef struct AcpiMiscInfo {
 110    bool is_piix4;
 111    bool has_hpet;
 112    TPMVersion tpm_version;
 113    const unsigned char *dsdt_code;
 114    unsigned dsdt_size;
 115    uint16_t pvpanic_port;
 116    uint16_t applesmc_io_base;
 117} AcpiMiscInfo;
 118
 119typedef struct AcpiBuildPciBusHotplugState {
 120    GArray *device_table;
 121    GArray *notify_table;
 122    struct AcpiBuildPciBusHotplugState *parent;
 123    bool pcihp_bridge_en;
 124} AcpiBuildPciBusHotplugState;
 125
 126static void acpi_get_pm_info(AcpiPmInfo *pm)
 127{
 128    Object *piix = piix4_pm_find();
 129    Object *lpc = ich9_lpc_find();
 130    Object *obj = NULL;
 131    QObject *o;
 132
 133    pm->force_rev1_fadt = false;
 134    pm->cpu_hp_io_base = 0;
 135    pm->pcihp_io_base = 0;
 136    pm->pcihp_io_len = 0;
 137    if (piix) {
 138        /* w2k requires FADT(rev1) or it won't boot, keep PC compatible */
 139        pm->force_rev1_fadt = true;
 140        obj = piix;
 141        pm->cpu_hp_io_base = PIIX4_CPU_HOTPLUG_IO_BASE;
 142        pm->pcihp_io_base =
 143            object_property_get_uint(obj, ACPI_PCIHP_IO_BASE_PROP, NULL);
 144        pm->pcihp_io_len =
 145            object_property_get_uint(obj, ACPI_PCIHP_IO_LEN_PROP, NULL);
 146    }
 147    if (lpc) {
 148        obj = lpc;
 149        pm->cpu_hp_io_base = ICH9_CPU_HOTPLUG_IO_BASE;
 150    }
 151    assert(obj);
 152
 153    /* Fill in optional s3/s4 related properties */
 154    o = object_property_get_qobject(obj, ACPI_PM_PROP_S3_DISABLED, NULL);
 155    if (o) {
 156        pm->s3_disabled = qnum_get_uint(qobject_to_qnum(o));
 157    } else {
 158        pm->s3_disabled = false;
 159    }
 160    qobject_decref(o);
 161    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL);
 162    if (o) {
 163        pm->s4_disabled = qnum_get_uint(qobject_to_qnum(o));
 164    } else {
 165        pm->s4_disabled = false;
 166    }
 167    qobject_decref(o);
 168    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL);
 169    if (o) {
 170        pm->s4_val = qnum_get_uint(qobject_to_qnum(o));
 171    } else {
 172        pm->s4_val = false;
 173    }
 174    qobject_decref(o);
 175
 176    /* Fill in mandatory properties */
 177    pm->sci_int = object_property_get_uint(obj, ACPI_PM_PROP_SCI_INT, NULL);
 178
 179    pm->acpi_enable_cmd = object_property_get_uint(obj,
 180                                                   ACPI_PM_PROP_ACPI_ENABLE_CMD,
 181                                                   NULL);
 182    pm->acpi_disable_cmd =
 183        object_property_get_uint(obj,
 184                                 ACPI_PM_PROP_ACPI_DISABLE_CMD,
 185                                 NULL);
 186    pm->io_base = object_property_get_uint(obj, ACPI_PM_PROP_PM_IO_BASE,
 187                                           NULL);
 188    pm->gpe0_blk = object_property_get_uint(obj, ACPI_PM_PROP_GPE0_BLK,
 189                                            NULL);
 190    pm->gpe0_blk_len = object_property_get_uint(obj, ACPI_PM_PROP_GPE0_BLK_LEN,
 191                                                NULL);
 192    pm->pcihp_bridge_en =
 193        object_property_get_bool(obj, "acpi-pci-hotplug-with-bridge-support",
 194                                 NULL);
 195}
 196
 197static void acpi_get_misc_info(AcpiMiscInfo *info)
 198{
 199    Object *piix = piix4_pm_find();
 200    Object *lpc = ich9_lpc_find();
 201    assert(!!piix != !!lpc);
 202
 203    if (piix) {
 204        info->is_piix4 = true;
 205    }
 206    if (lpc) {
 207        info->is_piix4 = false;
 208    }
 209
 210    info->has_hpet = hpet_find();
 211    info->tpm_version = tpm_get_version();
 212    info->pvpanic_port = pvpanic_port();
 213    info->applesmc_io_base = applesmc_port();
 214}
 215
 216/*
 217 * Because of the PXB hosts we cannot simply query TYPE_PCI_HOST_BRIDGE.
 218 * On i386 arch we only have two pci hosts, so we can look only for them.
 219 */
 220static Object *acpi_get_i386_pci_host(void)
 221{
 222    PCIHostState *host;
 223
 224    host = OBJECT_CHECK(PCIHostState,
 225                        object_resolve_path("/machine/i440fx", NULL),
 226                        TYPE_PCI_HOST_BRIDGE);
 227    if (!host) {
 228        host = OBJECT_CHECK(PCIHostState,
 229                            object_resolve_path("/machine/q35", NULL),
 230                            TYPE_PCI_HOST_BRIDGE);
 231    }
 232
 233    return OBJECT(host);
 234}
 235
 236static void acpi_get_pci_holes(Range *hole, Range *hole64)
 237{
 238    Object *pci_host;
 239
 240    pci_host = acpi_get_i386_pci_host();
 241    g_assert(pci_host);
 242
 243    range_set_bounds1(hole,
 244                      object_property_get_uint(pci_host,
 245                                               PCI_HOST_PROP_PCI_HOLE_START,
 246                                               NULL),
 247                      object_property_get_uint(pci_host,
 248                                               PCI_HOST_PROP_PCI_HOLE_END,
 249                                               NULL));
 250    range_set_bounds1(hole64,
 251                      object_property_get_uint(pci_host,
 252                                               PCI_HOST_PROP_PCI_HOLE64_START,
 253                                               NULL),
 254                      object_property_get_uint(pci_host,
 255                                               PCI_HOST_PROP_PCI_HOLE64_END,
 256                                               NULL));
 257}
 258
 259#define ACPI_PORT_SMI_CMD           0x00b2 /* TODO: this is APM_CNT_IOPORT */
 260
 261static void acpi_align_size(GArray *blob, unsigned align)
 262{
 263    /* Align size to multiple of given size. This reduces the chance
 264     * we need to change size in the future (breaking cross version migration).
 265     */
 266    g_array_set_size(blob, ROUND_UP(acpi_data_len(blob), align));
 267}
 268
 269/* FACS */
 270static void
 271build_facs(GArray *table_data, BIOSLinker *linker)
 272{
 273    AcpiFacsDescriptorRev1 *facs = acpi_data_push(table_data, sizeof *facs);
 274    memcpy(&facs->signature, "FACS", 4);
 275    facs->length = cpu_to_le32(sizeof(*facs));
 276}
 277
 278/* Load chipset information in FADT */
 279static void fadt_setup(AcpiFadtDescriptorRev3 *fadt, AcpiPmInfo *pm)
 280{
 281    fadt->model = 1;
 282    fadt->reserved1 = 0;
 283    fadt->sci_int = cpu_to_le16(pm->sci_int);
 284    fadt->smi_cmd = cpu_to_le32(ACPI_PORT_SMI_CMD);
 285    fadt->acpi_enable = pm->acpi_enable_cmd;
 286    fadt->acpi_disable = pm->acpi_disable_cmd;
 287    /* EVT, CNT, TMR offset matches hw/acpi/core.c */
 288    fadt->pm1a_evt_blk = cpu_to_le32(pm->io_base);
 289    fadt->pm1a_cnt_blk = cpu_to_le32(pm->io_base + 0x04);
 290    fadt->pm_tmr_blk = cpu_to_le32(pm->io_base + 0x08);
 291    fadt->gpe0_blk = cpu_to_le32(pm->gpe0_blk);
 292    /* EVT, CNT, TMR length matches hw/acpi/core.c */
 293    fadt->pm1_evt_len = 4;
 294    fadt->pm1_cnt_len = 2;
 295    fadt->pm_tmr_len = 4;
 296    fadt->gpe0_blk_len = pm->gpe0_blk_len;
 297    fadt->plvl2_lat = cpu_to_le16(0xfff); /* C2 state not supported */
 298    fadt->plvl3_lat = cpu_to_le16(0xfff); /* C3 state not supported */
 299    fadt->flags = cpu_to_le32((1 << ACPI_FADT_F_WBINVD) |
 300                              (1 << ACPI_FADT_F_PROC_C1) |
 301                              (1 << ACPI_FADT_F_SLP_BUTTON) |
 302                              (1 << ACPI_FADT_F_RTC_S4));
 303    fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_USE_PLATFORM_CLOCK);
 304    /* APIC destination mode ("Flat Logical") has an upper limit of 8 CPUs
 305     * For more than 8 CPUs, "Clustered Logical" mode has to be used
 306     */
 307    if (max_cpus > 8) {
 308        fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_FORCE_APIC_CLUSTER_MODEL);
 309    }
 310    fadt->century = RTC_CENTURY;
 311    if (pm->force_rev1_fadt) {
 312        return;
 313    }
 314
 315    fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_RESET_REG_SUP);
 316    fadt->reset_value = 0xf;
 317    fadt->reset_register.space_id = AML_SYSTEM_IO;
 318    fadt->reset_register.bit_width = 8;
 319    fadt->reset_register.address = cpu_to_le64(ICH9_RST_CNT_IOPORT);
 320    /* The above need not be conditional on machine type because the reset port
 321     * happens to be the same on PIIX (pc) and ICH9 (q35). */
 322    QEMU_BUILD_BUG_ON(ICH9_RST_CNT_IOPORT != RCR_IOPORT);
 323
 324    fadt->xpm1a_event_block.space_id = AML_SYSTEM_IO;
 325    fadt->xpm1a_event_block.bit_width = fadt->pm1_evt_len * 8;
 326    fadt->xpm1a_event_block.address = cpu_to_le64(pm->io_base);
 327
 328    fadt->xpm1a_control_block.space_id = AML_SYSTEM_IO;
 329    fadt->xpm1a_control_block.bit_width = fadt->pm1_cnt_len * 8;
 330    fadt->xpm1a_control_block.address = cpu_to_le64(pm->io_base + 0x4);
 331
 332    fadt->xpm_timer_block.space_id = AML_SYSTEM_IO;
 333    fadt->xpm_timer_block.bit_width = fadt->pm_tmr_len * 8;
 334    fadt->xpm_timer_block.address = cpu_to_le64(pm->io_base + 0x8);
 335
 336    fadt->xgpe0_block.space_id = AML_SYSTEM_IO;
 337    fadt->xgpe0_block.bit_width = pm->gpe0_blk_len * 8;
 338    fadt->xgpe0_block.address = cpu_to_le64(pm->gpe0_blk);
 339}
 340
 341
 342/* FADT */
 343static void
 344build_fadt(GArray *table_data, BIOSLinker *linker, AcpiPmInfo *pm,
 345           unsigned facs_tbl_offset, unsigned dsdt_tbl_offset,
 346           const char *oem_id, const char *oem_table_id)
 347{
 348    AcpiFadtDescriptorRev3 *fadt = acpi_data_push(table_data, sizeof(*fadt));
 349    unsigned fw_ctrl_offset = (char *)&fadt->firmware_ctrl - table_data->data;
 350    unsigned dsdt_entry_offset = (char *)&fadt->dsdt - table_data->data;
 351    unsigned xdsdt_entry_offset = (char *)&fadt->x_dsdt - table_data->data;
 352    int fadt_size = sizeof(*fadt);
 353    int rev = 3;
 354
 355    /* FACS address to be filled by Guest linker */
 356    bios_linker_loader_add_pointer(linker,
 357        ACPI_BUILD_TABLE_FILE, fw_ctrl_offset, sizeof(fadt->firmware_ctrl),
 358        ACPI_BUILD_TABLE_FILE, facs_tbl_offset);
 359
 360    /* DSDT address to be filled by Guest linker */
 361    fadt_setup(fadt, pm);
 362    bios_linker_loader_add_pointer(linker,
 363        ACPI_BUILD_TABLE_FILE, dsdt_entry_offset, sizeof(fadt->dsdt),
 364        ACPI_BUILD_TABLE_FILE, dsdt_tbl_offset);
 365    if (pm->force_rev1_fadt) {
 366        rev = 1;
 367        fadt_size = offsetof(typeof(*fadt), reset_register);
 368    } else {
 369        bios_linker_loader_add_pointer(linker,
 370            ACPI_BUILD_TABLE_FILE, xdsdt_entry_offset, sizeof(fadt->x_dsdt),
 371            ACPI_BUILD_TABLE_FILE, dsdt_tbl_offset);
 372    }
 373
 374    build_header(linker, table_data,
 375                 (void *)fadt, "FACP", fadt_size, rev, oem_id, oem_table_id);
 376}
 377
 378void pc_madt_cpu_entry(AcpiDeviceIf *adev, int uid,
 379                       const CPUArchIdList *apic_ids, GArray *entry)
 380{
 381    uint32_t apic_id = apic_ids->cpus[uid].arch_id;
 382
 383    /* ACPI spec says that LAPIC entry for non present
 384     * CPU may be omitted from MADT or it must be marked
 385     * as disabled. However omitting non present CPU from
 386     * MADT breaks hotplug on linux. So possible CPUs
 387     * should be put in MADT but kept disabled.
 388     */
 389    if (apic_id < 255) {
 390        AcpiMadtProcessorApic *apic = acpi_data_push(entry, sizeof *apic);
 391
 392        apic->type = ACPI_APIC_PROCESSOR;
 393        apic->length = sizeof(*apic);
 394        apic->processor_id = uid;
 395        apic->local_apic_id = apic_id;
 396        if (apic_ids->cpus[uid].cpu != NULL) {
 397            apic->flags = cpu_to_le32(1);
 398        } else {
 399            apic->flags = cpu_to_le32(0);
 400        }
 401    } else {
 402        AcpiMadtProcessorX2Apic *apic = acpi_data_push(entry, sizeof *apic);
 403
 404        apic->type = ACPI_APIC_LOCAL_X2APIC;
 405        apic->length = sizeof(*apic);
 406        apic->uid = cpu_to_le32(uid);
 407        apic->x2apic_id = cpu_to_le32(apic_id);
 408        if (apic_ids->cpus[uid].cpu != NULL) {
 409            apic->flags = cpu_to_le32(1);
 410        } else {
 411            apic->flags = cpu_to_le32(0);
 412        }
 413    }
 414}
 415
 416static void
 417build_madt(GArray *table_data, BIOSLinker *linker, PCMachineState *pcms)
 418{
 419    MachineClass *mc = MACHINE_GET_CLASS(pcms);
 420    const CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(MACHINE(pcms));
 421    int madt_start = table_data->len;
 422    AcpiDeviceIfClass *adevc = ACPI_DEVICE_IF_GET_CLASS(pcms->acpi_dev);
 423    AcpiDeviceIf *adev = ACPI_DEVICE_IF(pcms->acpi_dev);
 424    bool x2apic_mode = false;
 425
 426    AcpiMultipleApicTable *madt;
 427    AcpiMadtIoApic *io_apic;
 428    AcpiMadtIntsrcovr *intsrcovr;
 429    int i;
 430
 431    madt = acpi_data_push(table_data, sizeof *madt);
 432    madt->local_apic_address = cpu_to_le32(APIC_DEFAULT_ADDRESS);
 433    madt->flags = cpu_to_le32(1);
 434
 435    for (i = 0; i < apic_ids->len; i++) {
 436        adevc->madt_cpu(adev, i, apic_ids, table_data);
 437        if (apic_ids->cpus[i].arch_id > 254) {
 438            x2apic_mode = true;
 439        }
 440    }
 441
 442    io_apic = acpi_data_push(table_data, sizeof *io_apic);
 443    io_apic->type = ACPI_APIC_IO;
 444    io_apic->length = sizeof(*io_apic);
 445    io_apic->io_apic_id = ACPI_BUILD_IOAPIC_ID;
 446    io_apic->address = cpu_to_le32(IO_APIC_DEFAULT_ADDRESS);
 447    io_apic->interrupt = cpu_to_le32(0);
 448
 449    if (pcms->apic_xrupt_override) {
 450        intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);
 451        intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;
 452        intsrcovr->length = sizeof(*intsrcovr);
 453        intsrcovr->source = 0;
 454        intsrcovr->gsi    = cpu_to_le32(2);
 455        intsrcovr->flags  = cpu_to_le16(0); /* conforms to bus specifications */
 456    }
 457    for (i = 1; i < 16; i++) {
 458#define ACPI_BUILD_PCI_IRQS ((1<<5) | (1<<9) | (1<<10) | (1<<11))
 459        if (!(ACPI_BUILD_PCI_IRQS & (1 << i))) {
 460            /* No need for a INT source override structure. */
 461            continue;
 462        }
 463        intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);
 464        intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;
 465        intsrcovr->length = sizeof(*intsrcovr);
 466        intsrcovr->source = i;
 467        intsrcovr->gsi    = cpu_to_le32(i);
 468        intsrcovr->flags  = cpu_to_le16(0xd); /* active high, level triggered */
 469    }
 470
 471    if (x2apic_mode) {
 472        AcpiMadtLocalX2ApicNmi *local_nmi;
 473
 474        local_nmi = acpi_data_push(table_data, sizeof *local_nmi);
 475        local_nmi->type   = ACPI_APIC_LOCAL_X2APIC_NMI;
 476        local_nmi->length = sizeof(*local_nmi);
 477        local_nmi->uid    = 0xFFFFFFFF; /* all processors */
 478        local_nmi->flags  = cpu_to_le16(0);
 479        local_nmi->lint   = 1; /* ACPI_LINT1 */
 480    } else {
 481        AcpiMadtLocalNmi *local_nmi;
 482
 483        local_nmi = acpi_data_push(table_data, sizeof *local_nmi);
 484        local_nmi->type         = ACPI_APIC_LOCAL_NMI;
 485        local_nmi->length       = sizeof(*local_nmi);
 486        local_nmi->processor_id = 0xff; /* all processors */
 487        local_nmi->flags        = cpu_to_le16(0);
 488        local_nmi->lint         = 1; /* ACPI_LINT1 */
 489    }
 490
 491    build_header(linker, table_data,
 492                 (void *)(table_data->data + madt_start), "APIC",
 493                 table_data->len - madt_start, 1, NULL, NULL);
 494}
 495
 496/* Assign BSEL property to all buses.  In the future, this can be changed
 497 * to only assign to buses that support hotplug.
 498 */
 499static void *acpi_set_bsel(PCIBus *bus, void *opaque)
 500{
 501    unsigned *bsel_alloc = opaque;
 502    unsigned *bus_bsel;
 503
 504    if (qbus_is_hotpluggable(BUS(bus))) {
 505        bus_bsel = g_malloc(sizeof *bus_bsel);
 506
 507        *bus_bsel = (*bsel_alloc)++;
 508        object_property_add_uint32_ptr(OBJECT(bus), ACPI_PCIHP_PROP_BSEL,
 509                                       bus_bsel, &error_abort);
 510    }
 511
 512    return bsel_alloc;
 513}
 514
 515static void acpi_set_pci_info(void)
 516{
 517    PCIBus *bus = find_i440fx(); /* TODO: Q35 support */
 518    unsigned bsel_alloc = ACPI_PCIHP_BSEL_DEFAULT;
 519
 520    if (bus) {
 521        /* Scan all PCI buses. Set property to enable acpi based hotplug. */
 522        pci_for_each_bus_depth_first(bus, acpi_set_bsel, NULL, &bsel_alloc);
 523    }
 524}
 525
 526static void build_append_pcihp_notify_entry(Aml *method, int slot)
 527{
 528    Aml *if_ctx;
 529    int32_t devfn = PCI_DEVFN(slot, 0);
 530
 531    if_ctx = aml_if(aml_and(aml_arg(0), aml_int(0x1U << slot), NULL));
 532    aml_append(if_ctx, aml_notify(aml_name("S%.02X", devfn), aml_arg(1)));
 533    aml_append(method, if_ctx);
 534}
 535
 536static void build_append_pci_bus_devices(Aml *parent_scope, PCIBus *bus,
 537                                         bool pcihp_bridge_en)
 538{
 539    Aml *dev, *notify_method, *method;
 540    QObject *bsel;
 541    PCIBus *sec;
 542    int i;
 543
 544    bsel = object_property_get_qobject(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, NULL);
 545    if (bsel) {
 546        uint64_t bsel_val = qnum_get_uint(qobject_to_qnum(bsel));
 547
 548        aml_append(parent_scope, aml_name_decl("BSEL", aml_int(bsel_val)));
 549        notify_method = aml_method("DVNT", 2, AML_NOTSERIALIZED);
 550    }
 551
 552    for (i = 0; i < ARRAY_SIZE(bus->devices); i += PCI_FUNC_MAX) {
 553        DeviceClass *dc;
 554        PCIDeviceClass *pc;
 555        PCIDevice *pdev = bus->devices[i];
 556        int slot = PCI_SLOT(i);
 557        bool hotplug_enabled_dev;
 558        bool bridge_in_acpi;
 559
 560        if (!pdev) {
 561            if (bsel) { /* add hotplug slots for non present devices */
 562                dev = aml_device("S%.02X", PCI_DEVFN(slot, 0));
 563                aml_append(dev, aml_name_decl("_SUN", aml_int(slot)));
 564                aml_append(dev, aml_name_decl("_ADR", aml_int(slot << 16)));
 565                method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);
 566                aml_append(method,
 567                    aml_call2("PCEJ", aml_name("BSEL"), aml_name("_SUN"))
 568                );
 569                aml_append(dev, method);
 570                aml_append(parent_scope, dev);
 571
 572                build_append_pcihp_notify_entry(notify_method, slot);
 573            }
 574            continue;
 575        }
 576
 577        pc = PCI_DEVICE_GET_CLASS(pdev);
 578        dc = DEVICE_GET_CLASS(pdev);
 579
 580        /* When hotplug for bridges is enabled, bridges are
 581         * described in ACPI separately (see build_pci_bus_end).
 582         * In this case they aren't themselves hot-pluggable.
 583         * Hotplugged bridges *are* hot-pluggable.
 584         */
 585        bridge_in_acpi = pc->is_bridge && pcihp_bridge_en &&
 586            !DEVICE(pdev)->hotplugged;
 587
 588        hotplug_enabled_dev = bsel && dc->hotpluggable && !bridge_in_acpi;
 589
 590        if (pc->class_id == PCI_CLASS_BRIDGE_ISA) {
 591            continue;
 592        }
 593
 594        /* start to compose PCI slot descriptor */
 595        dev = aml_device("S%.02X", PCI_DEVFN(slot, 0));
 596        aml_append(dev, aml_name_decl("_ADR", aml_int(slot << 16)));
 597
 598        if (pc->class_id == PCI_CLASS_DISPLAY_VGA) {
 599            /* add VGA specific AML methods */
 600            int s3d;
 601
 602            if (object_dynamic_cast(OBJECT(pdev), "qxl-vga")) {
 603                s3d = 3;
 604            } else {
 605                s3d = 0;
 606            }
 607
 608            method = aml_method("_S1D", 0, AML_NOTSERIALIZED);
 609            aml_append(method, aml_return(aml_int(0)));
 610            aml_append(dev, method);
 611
 612            method = aml_method("_S2D", 0, AML_NOTSERIALIZED);
 613            aml_append(method, aml_return(aml_int(0)));
 614            aml_append(dev, method);
 615
 616            method = aml_method("_S3D", 0, AML_NOTSERIALIZED);
 617            aml_append(method, aml_return(aml_int(s3d)));
 618            aml_append(dev, method);
 619        } else if (hotplug_enabled_dev) {
 620            /* add _SUN/_EJ0 to make slot hotpluggable  */
 621            aml_append(dev, aml_name_decl("_SUN", aml_int(slot)));
 622
 623            method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);
 624            aml_append(method,
 625                aml_call2("PCEJ", aml_name("BSEL"), aml_name("_SUN"))
 626            );
 627            aml_append(dev, method);
 628
 629            if (bsel) {
 630                build_append_pcihp_notify_entry(notify_method, slot);
 631            }
 632        } else if (bridge_in_acpi) {
 633            /*
 634             * device is coldplugged bridge,
 635             * add child device descriptions into its scope
 636             */
 637            PCIBus *sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
 638
 639            build_append_pci_bus_devices(dev, sec_bus, pcihp_bridge_en);
 640        }
 641        /* slot descriptor has been composed, add it into parent context */
 642        aml_append(parent_scope, dev);
 643    }
 644
 645    if (bsel) {
 646        aml_append(parent_scope, notify_method);
 647    }
 648
 649    /* Append PCNT method to notify about events on local and child buses.
 650     * Add unconditionally for root since DSDT expects it.
 651     */
 652    method = aml_method("PCNT", 0, AML_NOTSERIALIZED);
 653
 654    /* If bus supports hotplug select it and notify about local events */
 655    if (bsel) {
 656        uint64_t bsel_val = qnum_get_uint(qobject_to_qnum(bsel));
 657
 658        aml_append(method, aml_store(aml_int(bsel_val), aml_name("BNUM")));
 659        aml_append(method,
 660            aml_call2("DVNT", aml_name("PCIU"), aml_int(1) /* Device Check */)
 661        );
 662        aml_append(method,
 663            aml_call2("DVNT", aml_name("PCID"), aml_int(3)/* Eject Request */)
 664        );
 665    }
 666
 667    /* Notify about child bus events in any case */
 668    if (pcihp_bridge_en) {
 669        QLIST_FOREACH(sec, &bus->child, sibling) {
 670            int32_t devfn = sec->parent_dev->devfn;
 671
 672            if (pci_bus_is_root(sec) || pci_bus_is_express(sec)) {
 673                continue;
 674            }
 675
 676            aml_append(method, aml_name("^S%.02X.PCNT", devfn));
 677        }
 678    }
 679    aml_append(parent_scope, method);
 680    qobject_decref(bsel);
 681}
 682
 683/**
 684 * build_prt_entry:
 685 * @link_name: link name for PCI route entry
 686 *
 687 * build AML package containing a PCI route entry for @link_name
 688 */
 689static Aml *build_prt_entry(const char *link_name)
 690{
 691    Aml *a_zero = aml_int(0);
 692    Aml *pkg = aml_package(4);
 693    aml_append(pkg, a_zero);
 694    aml_append(pkg, a_zero);
 695    aml_append(pkg, aml_name("%s", link_name));
 696    aml_append(pkg, a_zero);
 697    return pkg;
 698}
 699
 700/*
 701 * initialize_route - Initialize the interrupt routing rule
 702 * through a specific LINK:
 703 *  if (lnk_idx == idx)
 704 *      route using link 'link_name'
 705 */
 706static Aml *initialize_route(Aml *route, const char *link_name,
 707                             Aml *lnk_idx, int idx)
 708{
 709    Aml *if_ctx = aml_if(aml_equal(lnk_idx, aml_int(idx)));
 710    Aml *pkg = build_prt_entry(link_name);
 711
 712    aml_append(if_ctx, aml_store(pkg, route));
 713
 714    return if_ctx;
 715}
 716
 717/*
 718 * build_prt - Define interrupt rounting rules
 719 *
 720 * Returns an array of 128 routes, one for each device,
 721 * based on device location.
 722 * The main goal is to equaly distribute the interrupts
 723 * over the 4 existing ACPI links (works only for i440fx).
 724 * The hash function is  (slot + pin) & 3 -> "LNK[D|A|B|C]".
 725 *
 726 */
 727static Aml *build_prt(bool is_pci0_prt)
 728{
 729    Aml *method, *while_ctx, *pin, *res;
 730
 731    method = aml_method("_PRT", 0, AML_NOTSERIALIZED);
 732    res = aml_local(0);
 733    pin = aml_local(1);
 734    aml_append(method, aml_store(aml_package(128), res));
 735    aml_append(method, aml_store(aml_int(0), pin));
 736
 737    /* while (pin < 128) */
 738    while_ctx = aml_while(aml_lless(pin, aml_int(128)));
 739    {
 740        Aml *slot = aml_local(2);
 741        Aml *lnk_idx = aml_local(3);
 742        Aml *route = aml_local(4);
 743
 744        /* slot = pin >> 2 */
 745        aml_append(while_ctx,
 746                   aml_store(aml_shiftright(pin, aml_int(2), NULL), slot));
 747        /* lnk_idx = (slot + pin) & 3 */
 748        aml_append(while_ctx,
 749            aml_store(aml_and(aml_add(pin, slot, NULL), aml_int(3), NULL),
 750                      lnk_idx));
 751
 752        /* route[2] = "LNK[D|A|B|C]", selection based on pin % 3  */
 753        aml_append(while_ctx, initialize_route(route, "LNKD", lnk_idx, 0));
 754        if (is_pci0_prt) {
 755            Aml *if_device_1, *if_pin_4, *else_pin_4;
 756
 757            /* device 1 is the power-management device, needs SCI */
 758            if_device_1 = aml_if(aml_equal(lnk_idx, aml_int(1)));
 759            {
 760                if_pin_4 = aml_if(aml_equal(pin, aml_int(4)));
 761                {
 762                    aml_append(if_pin_4,
 763                        aml_store(build_prt_entry("LNKS"), route));
 764                }
 765                aml_append(if_device_1, if_pin_4);
 766                else_pin_4 = aml_else();
 767                {
 768                    aml_append(else_pin_4,
 769                        aml_store(build_prt_entry("LNKA"), route));
 770                }
 771                aml_append(if_device_1, else_pin_4);
 772            }
 773            aml_append(while_ctx, if_device_1);
 774        } else {
 775            aml_append(while_ctx, initialize_route(route, "LNKA", lnk_idx, 1));
 776        }
 777        aml_append(while_ctx, initialize_route(route, "LNKB", lnk_idx, 2));
 778        aml_append(while_ctx, initialize_route(route, "LNKC", lnk_idx, 3));
 779
 780        /* route[0] = 0x[slot]FFFF */
 781        aml_append(while_ctx,
 782            aml_store(aml_or(aml_shiftleft(slot, aml_int(16)), aml_int(0xFFFF),
 783                             NULL),
 784                      aml_index(route, aml_int(0))));
 785        /* route[1] = pin & 3 */
 786        aml_append(while_ctx,
 787            aml_store(aml_and(pin, aml_int(3), NULL),
 788                      aml_index(route, aml_int(1))));
 789        /* res[pin] = route */
 790        aml_append(while_ctx, aml_store(route, aml_index(res, pin)));
 791        /* pin++ */
 792        aml_append(while_ctx, aml_increment(pin));
 793    }
 794    aml_append(method, while_ctx);
 795    /* return res*/
 796    aml_append(method, aml_return(res));
 797
 798    return method;
 799}
 800
 801typedef struct CrsRangeEntry {
 802    uint64_t base;
 803    uint64_t limit;
 804} CrsRangeEntry;
 805
 806static void crs_range_insert(GPtrArray *ranges, uint64_t base, uint64_t limit)
 807{
 808    CrsRangeEntry *entry;
 809
 810    entry = g_malloc(sizeof(*entry));
 811    entry->base = base;
 812    entry->limit = limit;
 813
 814    g_ptr_array_add(ranges, entry);
 815}
 816
 817static void crs_range_free(gpointer data)
 818{
 819    CrsRangeEntry *entry = (CrsRangeEntry *)data;
 820    g_free(entry);
 821}
 822
 823typedef struct CrsRangeSet {
 824    GPtrArray *io_ranges;
 825    GPtrArray *mem_ranges;
 826    GPtrArray *mem_64bit_ranges;
 827 } CrsRangeSet;
 828
 829static void crs_range_set_init(CrsRangeSet *range_set)
 830{
 831    range_set->io_ranges = g_ptr_array_new_with_free_func(crs_range_free);
 832    range_set->mem_ranges = g_ptr_array_new_with_free_func(crs_range_free);
 833    range_set->mem_64bit_ranges =
 834            g_ptr_array_new_with_free_func(crs_range_free);
 835}
 836
 837static void crs_range_set_free(CrsRangeSet *range_set)
 838{
 839    g_ptr_array_free(range_set->io_ranges, true);
 840    g_ptr_array_free(range_set->mem_ranges, true);
 841    g_ptr_array_free(range_set->mem_64bit_ranges, true);
 842}
 843
 844static gint crs_range_compare(gconstpointer a, gconstpointer b)
 845{
 846     CrsRangeEntry *entry_a = *(CrsRangeEntry **)a;
 847     CrsRangeEntry *entry_b = *(CrsRangeEntry **)b;
 848
 849     return (int64_t)entry_a->base - (int64_t)entry_b->base;
 850}
 851
 852/*
 853 * crs_replace_with_free_ranges - given the 'used' ranges within [start - end]
 854 * interval, computes the 'free' ranges from the same interval.
 855 * Example: If the input array is { [a1 - a2],[b1 - b2] }, the function
 856 * will return { [base - a1], [a2 - b1], [b2 - limit] }.
 857 */
 858static void crs_replace_with_free_ranges(GPtrArray *ranges,
 859                                         uint64_t start, uint64_t end)
 860{
 861    GPtrArray *free_ranges = g_ptr_array_new();
 862    uint64_t free_base = start;
 863    int i;
 864
 865    g_ptr_array_sort(ranges, crs_range_compare);
 866    for (i = 0; i < ranges->len; i++) {
 867        CrsRangeEntry *used = g_ptr_array_index(ranges, i);
 868
 869        if (free_base < used->base) {
 870            crs_range_insert(free_ranges, free_base, used->base - 1);
 871        }
 872
 873        free_base = used->limit + 1;
 874    }
 875
 876    if (free_base < end) {
 877        crs_range_insert(free_ranges, free_base, end);
 878    }
 879
 880    g_ptr_array_set_size(ranges, 0);
 881    for (i = 0; i < free_ranges->len; i++) {
 882        g_ptr_array_add(ranges, g_ptr_array_index(free_ranges, i));
 883    }
 884
 885    g_ptr_array_free(free_ranges, true);
 886}
 887
 888/*
 889 * crs_range_merge - merges adjacent ranges in the given array.
 890 * Array elements are deleted and replaced with the merged ranges.
 891 */
 892static void crs_range_merge(GPtrArray *range)
 893{
 894    GPtrArray *tmp =  g_ptr_array_new_with_free_func(crs_range_free);
 895    CrsRangeEntry *entry;
 896    uint64_t range_base, range_limit;
 897    int i;
 898
 899    if (!range->len) {
 900        return;
 901    }
 902
 903    g_ptr_array_sort(range, crs_range_compare);
 904
 905    entry = g_ptr_array_index(range, 0);
 906    range_base = entry->base;
 907    range_limit = entry->limit;
 908    for (i = 1; i < range->len; i++) {
 909        entry = g_ptr_array_index(range, i);
 910        if (entry->base - 1 == range_limit) {
 911            range_limit = entry->limit;
 912        } else {
 913            crs_range_insert(tmp, range_base, range_limit);
 914            range_base = entry->base;
 915            range_limit = entry->limit;
 916        }
 917    }
 918    crs_range_insert(tmp, range_base, range_limit);
 919
 920    g_ptr_array_set_size(range, 0);
 921    for (i = 0; i < tmp->len; i++) {
 922        entry = g_ptr_array_index(tmp, i);
 923        crs_range_insert(range, entry->base, entry->limit);
 924    }
 925    g_ptr_array_free(tmp, true);
 926}
 927
 928static Aml *build_crs(PCIHostState *host, CrsRangeSet *range_set)
 929{
 930    Aml *crs = aml_resource_template();
 931    CrsRangeSet temp_range_set;
 932    CrsRangeEntry *entry;
 933    uint8_t max_bus = pci_bus_num(host->bus);
 934    uint8_t type;
 935    int devfn;
 936    int i;
 937
 938    crs_range_set_init(&temp_range_set);
 939    for (devfn = 0; devfn < ARRAY_SIZE(host->bus->devices); devfn++) {
 940        uint64_t range_base, range_limit;
 941        PCIDevice *dev = host->bus->devices[devfn];
 942
 943        if (!dev) {
 944            continue;
 945        }
 946
 947        for (i = 0; i < PCI_NUM_REGIONS; i++) {
 948            PCIIORegion *r = &dev->io_regions[i];
 949
 950            range_base = r->addr;
 951            range_limit = r->addr + r->size - 1;
 952
 953            /*
 954             * Work-around for old bioses
 955             * that do not support multiple root buses
 956             */
 957            if (!range_base || range_base > range_limit) {
 958                continue;
 959            }
 960
 961            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
 962                crs_range_insert(temp_range_set.io_ranges,
 963                                 range_base, range_limit);
 964            } else { /* "memory" */
 965                crs_range_insert(temp_range_set.mem_ranges,
 966                                 range_base, range_limit);
 967            }
 968        }
 969
 970        type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
 971        if (type == PCI_HEADER_TYPE_BRIDGE) {
 972            uint8_t subordinate = dev->config[PCI_SUBORDINATE_BUS];
 973            if (subordinate > max_bus) {
 974                max_bus = subordinate;
 975            }
 976
 977            range_base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
 978            range_limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
 979
 980            /*
 981             * Work-around for old bioses
 982             * that do not support multiple root buses
 983             */
 984            if (range_base && range_base <= range_limit) {
 985                crs_range_insert(temp_range_set.io_ranges,
 986                                 range_base, range_limit);
 987            }
 988
 989            range_base =
 990                pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
 991            range_limit =
 992                pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
 993
 994            /*
 995             * Work-around for old bioses
 996             * that do not support multiple root buses
 997             */
 998            if (range_base && range_base <= range_limit) {
 999                uint64_t length = range_limit - range_base + 1;
1000                if (range_limit <= UINT32_MAX && length <= UINT32_MAX) {
1001                    crs_range_insert(temp_range_set.mem_ranges,
1002                                     range_base, range_limit);
1003                } else {
1004                    crs_range_insert(temp_range_set.mem_64bit_ranges,
1005                                     range_base, range_limit);
1006                }
1007            }
1008
1009            range_base =
1010                pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1011            range_limit =
1012                pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1013
1014            /*
1015             * Work-around for old bioses
1016             * that do not support multiple root buses
1017             */
1018            if (range_base && range_base <= range_limit) {
1019                uint64_t length = range_limit - range_base + 1;
1020                if (range_limit <= UINT32_MAX && length <= UINT32_MAX) {
1021                    crs_range_insert(temp_range_set.mem_ranges,
1022                                     range_base, range_limit);
1023                } else {
1024                    crs_range_insert(temp_range_set.mem_64bit_ranges,
1025                                     range_base, range_limit);
1026                }
1027            }
1028        }
1029    }
1030
1031    crs_range_merge(temp_range_set.io_ranges);
1032    for (i = 0; i < temp_range_set.io_ranges->len; i++) {
1033        entry = g_ptr_array_index(temp_range_set.io_ranges, i);
1034        aml_append(crs,
1035                   aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
1036                               AML_POS_DECODE, AML_ENTIRE_RANGE,
1037                               0, entry->base, entry->limit, 0,
1038                               entry->limit - entry->base + 1));
1039        crs_range_insert(range_set->io_ranges, entry->base, entry->limit);
1040    }
1041
1042    crs_range_merge(temp_range_set.mem_ranges);
1043    for (i = 0; i < temp_range_set.mem_ranges->len; i++) {
1044        entry = g_ptr_array_index(temp_range_set.mem_ranges, i);
1045        aml_append(crs,
1046                   aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED,
1047                                    AML_MAX_FIXED, AML_NON_CACHEABLE,
1048                                    AML_READ_WRITE,
1049                                    0, entry->base, entry->limit, 0,
1050                                    entry->limit - entry->base + 1));
1051        crs_range_insert(range_set->mem_ranges, entry->base, entry->limit);
1052    }
1053
1054    crs_range_merge(temp_range_set.mem_64bit_ranges);
1055    for (i = 0; i < temp_range_set.mem_64bit_ranges->len; i++) {
1056        entry = g_ptr_array_index(temp_range_set.mem_64bit_ranges, i);
1057        aml_append(crs,
1058                   aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED,
1059                                    AML_MAX_FIXED, AML_NON_CACHEABLE,
1060                                    AML_READ_WRITE,
1061                                    0, entry->base, entry->limit, 0,
1062                                    entry->limit - entry->base + 1));
1063        crs_range_insert(range_set->mem_64bit_ranges,
1064                         entry->base, entry->limit);
1065    }
1066
1067    crs_range_set_free(&temp_range_set);
1068
1069    aml_append(crs,
1070        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,
1071                            0,
1072                            pci_bus_num(host->bus),
1073                            max_bus,
1074                            0,
1075                            max_bus - pci_bus_num(host->bus) + 1));
1076
1077    return crs;
1078}
1079
1080static void build_hpet_aml(Aml *table)
1081{
1082    Aml *crs;
1083    Aml *field;
1084    Aml *method;
1085    Aml *if_ctx;
1086    Aml *scope = aml_scope("_SB");
1087    Aml *dev = aml_device("HPET");
1088    Aml *zero = aml_int(0);
1089    Aml *id = aml_local(0);
1090    Aml *period = aml_local(1);
1091
1092    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0103")));
1093    aml_append(dev, aml_name_decl("_UID", zero));
1094
1095    aml_append(dev,
1096        aml_operation_region("HPTM", AML_SYSTEM_MEMORY, aml_int(HPET_BASE),
1097                             HPET_LEN));
1098    field = aml_field("HPTM", AML_DWORD_ACC, AML_LOCK, AML_PRESERVE);
1099    aml_append(field, aml_named_field("VEND", 32));
1100    aml_append(field, aml_named_field("PRD", 32));
1101    aml_append(dev, field);
1102
1103    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1104    aml_append(method, aml_store(aml_name("VEND"), id));
1105    aml_append(method, aml_store(aml_name("PRD"), period));
1106    aml_append(method, aml_shiftright(id, aml_int(16), id));
1107    if_ctx = aml_if(aml_lor(aml_equal(id, zero),
1108                            aml_equal(id, aml_int(0xffff))));
1109    {
1110        aml_append(if_ctx, aml_return(zero));
1111    }
1112    aml_append(method, if_ctx);
1113
1114    if_ctx = aml_if(aml_lor(aml_equal(period, zero),
1115                            aml_lgreater(period, aml_int(100000000))));
1116    {
1117        aml_append(if_ctx, aml_return(zero));
1118    }
1119    aml_append(method, if_ctx);
1120
1121    aml_append(method, aml_return(aml_int(0x0F)));
1122    aml_append(dev, method);
1123
1124    crs = aml_resource_template();
1125    aml_append(crs, aml_memory32_fixed(HPET_BASE, HPET_LEN, AML_READ_ONLY));
1126    aml_append(dev, aml_name_decl("_CRS", crs));
1127
1128    aml_append(scope, dev);
1129    aml_append(table, scope);
1130}
1131
1132static Aml *build_fdinfo_aml(int idx, FloppyDriveType type)
1133{
1134    Aml *dev, *fdi;
1135    uint8_t maxc, maxh, maxs;
1136
1137    isa_fdc_get_drive_max_chs(type, &maxc, &maxh, &maxs);
1138
1139    dev = aml_device("FLP%c", 'A' + idx);
1140
1141    aml_append(dev, aml_name_decl("_ADR", aml_int(idx)));
1142
1143    fdi = aml_package(16);
1144    aml_append(fdi, aml_int(idx));  /* Drive Number */
1145    aml_append(fdi,
1146        aml_int(cmos_get_fd_drive_type(type)));  /* Device Type */
1147    /*
1148     * the values below are the limits of the drive, and are thus independent
1149     * of the inserted media
1150     */
1151    aml_append(fdi, aml_int(maxc));  /* Maximum Cylinder Number */
1152    aml_append(fdi, aml_int(maxs));  /* Maximum Sector Number */
1153    aml_append(fdi, aml_int(maxh));  /* Maximum Head Number */
1154    /*
1155     * SeaBIOS returns the below values for int 0x13 func 0x08 regardless of
1156     * the drive type, so shall we
1157     */
1158    aml_append(fdi, aml_int(0xAF));  /* disk_specify_1 */
1159    aml_append(fdi, aml_int(0x02));  /* disk_specify_2 */
1160    aml_append(fdi, aml_int(0x25));  /* disk_motor_wait */
1161    aml_append(fdi, aml_int(0x02));  /* disk_sector_siz */
1162    aml_append(fdi, aml_int(0x12));  /* disk_eot */
1163    aml_append(fdi, aml_int(0x1B));  /* disk_rw_gap */
1164    aml_append(fdi, aml_int(0xFF));  /* disk_dtl */
1165    aml_append(fdi, aml_int(0x6C));  /* disk_formt_gap */
1166    aml_append(fdi, aml_int(0xF6));  /* disk_fill */
1167    aml_append(fdi, aml_int(0x0F));  /* disk_head_sttl */
1168    aml_append(fdi, aml_int(0x08));  /* disk_motor_strt */
1169
1170    aml_append(dev, aml_name_decl("_FDI", fdi));
1171    return dev;
1172}
1173
1174static Aml *build_fdc_device_aml(ISADevice *fdc)
1175{
1176    int i;
1177    Aml *dev;
1178    Aml *crs;
1179
1180#define ACPI_FDE_MAX_FD 4
1181    uint32_t fde_buf[5] = {
1182        0, 0, 0, 0,     /* presence of floppy drives #0 - #3 */
1183        cpu_to_le32(2)  /* tape presence (2 == never present) */
1184    };
1185
1186    dev = aml_device("FDC0");
1187    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0700")));
1188
1189    crs = aml_resource_template();
1190    aml_append(crs, aml_io(AML_DECODE16, 0x03F2, 0x03F2, 0x00, 0x04));
1191    aml_append(crs, aml_io(AML_DECODE16, 0x03F7, 0x03F7, 0x00, 0x01));
1192    aml_append(crs, aml_irq_no_flags(6));
1193    aml_append(crs,
1194        aml_dma(AML_COMPATIBILITY, AML_NOTBUSMASTER, AML_TRANSFER8, 2));
1195    aml_append(dev, aml_name_decl("_CRS", crs));
1196
1197    for (i = 0; i < MIN(MAX_FD, ACPI_FDE_MAX_FD); i++) {
1198        FloppyDriveType type = isa_fdc_get_drive_type(fdc, i);
1199
1200        if (type < FLOPPY_DRIVE_TYPE_NONE) {
1201            fde_buf[i] = cpu_to_le32(1);  /* drive present */
1202            aml_append(dev, build_fdinfo_aml(i, type));
1203        }
1204    }
1205    aml_append(dev, aml_name_decl("_FDE",
1206               aml_buffer(sizeof(fde_buf), (uint8_t *)fde_buf)));
1207
1208    return dev;
1209}
1210
1211static Aml *build_rtc_device_aml(void)
1212{
1213    Aml *dev;
1214    Aml *crs;
1215
1216    dev = aml_device("RTC");
1217    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0B00")));
1218    crs = aml_resource_template();
1219    aml_append(crs, aml_io(AML_DECODE16, 0x0070, 0x0070, 0x10, 0x02));
1220    aml_append(crs, aml_irq_no_flags(8));
1221    aml_append(crs, aml_io(AML_DECODE16, 0x0072, 0x0072, 0x02, 0x06));
1222    aml_append(dev, aml_name_decl("_CRS", crs));
1223
1224    return dev;
1225}
1226
1227static Aml *build_kbd_device_aml(void)
1228{
1229    Aml *dev;
1230    Aml *crs;
1231    Aml *method;
1232
1233    dev = aml_device("KBD");
1234    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0303")));
1235
1236    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1237    aml_append(method, aml_return(aml_int(0x0f)));
1238    aml_append(dev, method);
1239
1240    crs = aml_resource_template();
1241    aml_append(crs, aml_io(AML_DECODE16, 0x0060, 0x0060, 0x01, 0x01));
1242    aml_append(crs, aml_io(AML_DECODE16, 0x0064, 0x0064, 0x01, 0x01));
1243    aml_append(crs, aml_irq_no_flags(1));
1244    aml_append(dev, aml_name_decl("_CRS", crs));
1245
1246    return dev;
1247}
1248
1249static Aml *build_mouse_device_aml(void)
1250{
1251    Aml *dev;
1252    Aml *crs;
1253    Aml *method;
1254
1255    dev = aml_device("MOU");
1256    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0F13")));
1257
1258    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1259    aml_append(method, aml_return(aml_int(0x0f)));
1260    aml_append(dev, method);
1261
1262    crs = aml_resource_template();
1263    aml_append(crs, aml_irq_no_flags(12));
1264    aml_append(dev, aml_name_decl("_CRS", crs));
1265
1266    return dev;
1267}
1268
1269static Aml *build_lpt_device_aml(void)
1270{
1271    Aml *dev;
1272    Aml *crs;
1273    Aml *method;
1274    Aml *if_ctx;
1275    Aml *else_ctx;
1276    Aml *zero = aml_int(0);
1277    Aml *is_present = aml_local(0);
1278
1279    dev = aml_device("LPT");
1280    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0400")));
1281
1282    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1283    aml_append(method, aml_store(aml_name("LPEN"), is_present));
1284    if_ctx = aml_if(aml_equal(is_present, zero));
1285    {
1286        aml_append(if_ctx, aml_return(aml_int(0x00)));
1287    }
1288    aml_append(method, if_ctx);
1289    else_ctx = aml_else();
1290    {
1291        aml_append(else_ctx, aml_return(aml_int(0x0f)));
1292    }
1293    aml_append(method, else_ctx);
1294    aml_append(dev, method);
1295
1296    crs = aml_resource_template();
1297    aml_append(crs, aml_io(AML_DECODE16, 0x0378, 0x0378, 0x08, 0x08));
1298    aml_append(crs, aml_irq_no_flags(7));
1299    aml_append(dev, aml_name_decl("_CRS", crs));
1300
1301    return dev;
1302}
1303
1304static Aml *build_com_device_aml(uint8_t uid)
1305{
1306    Aml *dev;
1307    Aml *crs;
1308    Aml *method;
1309    Aml *if_ctx;
1310    Aml *else_ctx;
1311    Aml *zero = aml_int(0);
1312    Aml *is_present = aml_local(0);
1313    const char *enabled_field = "CAEN";
1314    uint8_t irq = 4;
1315    uint16_t io_port = 0x03F8;
1316
1317    assert(uid == 1 || uid == 2);
1318    if (uid == 2) {
1319        enabled_field = "CBEN";
1320        irq = 3;
1321        io_port = 0x02F8;
1322    }
1323
1324    dev = aml_device("COM%d", uid);
1325    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0501")));
1326    aml_append(dev, aml_name_decl("_UID", aml_int(uid)));
1327
1328    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1329    aml_append(method, aml_store(aml_name("%s", enabled_field), is_present));
1330    if_ctx = aml_if(aml_equal(is_present, zero));
1331    {
1332        aml_append(if_ctx, aml_return(aml_int(0x00)));
1333    }
1334    aml_append(method, if_ctx);
1335    else_ctx = aml_else();
1336    {
1337        aml_append(else_ctx, aml_return(aml_int(0x0f)));
1338    }
1339    aml_append(method, else_ctx);
1340    aml_append(dev, method);
1341
1342    crs = aml_resource_template();
1343    aml_append(crs, aml_io(AML_DECODE16, io_port, io_port, 0x00, 0x08));
1344    aml_append(crs, aml_irq_no_flags(irq));
1345    aml_append(dev, aml_name_decl("_CRS", crs));
1346
1347    return dev;
1348}
1349
1350static void build_isa_devices_aml(Aml *table)
1351{
1352    ISADevice *fdc = pc_find_fdc0();
1353    bool ambiguous;
1354
1355    Aml *scope = aml_scope("_SB.PCI0.ISA");
1356    Object *obj = object_resolve_path_type("", TYPE_ISA_BUS, &ambiguous);
1357
1358    aml_append(scope, build_rtc_device_aml());
1359    aml_append(scope, build_kbd_device_aml());
1360    aml_append(scope, build_mouse_device_aml());
1361    if (fdc) {
1362        aml_append(scope, build_fdc_device_aml(fdc));
1363    }
1364    aml_append(scope, build_lpt_device_aml());
1365    aml_append(scope, build_com_device_aml(1));
1366    aml_append(scope, build_com_device_aml(2));
1367
1368    if (ambiguous) {
1369        error_report("Multiple ISA busses, unable to define IPMI ACPI data");
1370    } else if (!obj) {
1371        error_report("No ISA bus, unable to define IPMI ACPI data");
1372    } else {
1373        build_acpi_ipmi_devices(scope, BUS(obj));
1374    }
1375
1376    aml_append(table, scope);
1377}
1378
1379static void build_dbg_aml(Aml *table)
1380{
1381    Aml *field;
1382    Aml *method;
1383    Aml *while_ctx;
1384    Aml *scope = aml_scope("\\");
1385    Aml *buf = aml_local(0);
1386    Aml *len = aml_local(1);
1387    Aml *idx = aml_local(2);
1388
1389    aml_append(scope,
1390       aml_operation_region("DBG", AML_SYSTEM_IO, aml_int(0x0402), 0x01));
1391    field = aml_field("DBG", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
1392    aml_append(field, aml_named_field("DBGB", 8));
1393    aml_append(scope, field);
1394
1395    method = aml_method("DBUG", 1, AML_NOTSERIALIZED);
1396
1397    aml_append(method, aml_to_hexstring(aml_arg(0), buf));
1398    aml_append(method, aml_to_buffer(buf, buf));
1399    aml_append(method, aml_subtract(aml_sizeof(buf), aml_int(1), len));
1400    aml_append(method, aml_store(aml_int(0), idx));
1401
1402    while_ctx = aml_while(aml_lless(idx, len));
1403    aml_append(while_ctx,
1404        aml_store(aml_derefof(aml_index(buf, idx)), aml_name("DBGB")));
1405    aml_append(while_ctx, aml_increment(idx));
1406    aml_append(method, while_ctx);
1407
1408    aml_append(method, aml_store(aml_int(0x0A), aml_name("DBGB")));
1409    aml_append(scope, method);
1410
1411    aml_append(table, scope);
1412}
1413
1414static Aml *build_link_dev(const char *name, uint8_t uid, Aml *reg)
1415{
1416    Aml *dev;
1417    Aml *crs;
1418    Aml *method;
1419    uint32_t irqs[] = {5, 10, 11};
1420
1421    dev = aml_device("%s", name);
1422    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C0F")));
1423    aml_append(dev, aml_name_decl("_UID", aml_int(uid)));
1424
1425    crs = aml_resource_template();
1426    aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,
1427                                  AML_SHARED, irqs, ARRAY_SIZE(irqs)));
1428    aml_append(dev, aml_name_decl("_PRS", crs));
1429
1430    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1431    aml_append(method, aml_return(aml_call1("IQST", reg)));
1432    aml_append(dev, method);
1433
1434    method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
1435    aml_append(method, aml_or(reg, aml_int(0x80), reg));
1436    aml_append(dev, method);
1437
1438    method = aml_method("_CRS", 0, AML_NOTSERIALIZED);
1439    aml_append(method, aml_return(aml_call1("IQCR", reg)));
1440    aml_append(dev, method);
1441
1442    method = aml_method("_SRS", 1, AML_NOTSERIALIZED);
1443    aml_append(method, aml_create_dword_field(aml_arg(0), aml_int(5), "PRRI"));
1444    aml_append(method, aml_store(aml_name("PRRI"), reg));
1445    aml_append(dev, method);
1446
1447    return dev;
1448 }
1449
1450static Aml *build_gsi_link_dev(const char *name, uint8_t uid, uint8_t gsi)
1451{
1452    Aml *dev;
1453    Aml *crs;
1454    Aml *method;
1455    uint32_t irqs;
1456
1457    dev = aml_device("%s", name);
1458    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C0F")));
1459    aml_append(dev, aml_name_decl("_UID", aml_int(uid)));
1460
1461    crs = aml_resource_template();
1462    irqs = gsi;
1463    aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,
1464                                  AML_SHARED, &irqs, 1));
1465    aml_append(dev, aml_name_decl("_PRS", crs));
1466
1467    aml_append(dev, aml_name_decl("_CRS", crs));
1468
1469    /*
1470     * _DIS can be no-op because the interrupt cannot be disabled.
1471     */
1472    method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
1473    aml_append(dev, method);
1474
1475    method = aml_method("_SRS", 1, AML_NOTSERIALIZED);
1476    aml_append(dev, method);
1477
1478    return dev;
1479}
1480
1481/* _CRS method - get current settings */
1482static Aml *build_iqcr_method(bool is_piix4)
1483{
1484    Aml *if_ctx;
1485    uint32_t irqs;
1486    Aml *method = aml_method("IQCR", 1, AML_SERIALIZED);
1487    Aml *crs = aml_resource_template();
1488
1489    irqs = 0;
1490    aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL,
1491                                  AML_ACTIVE_HIGH, AML_SHARED, &irqs, 1));
1492    aml_append(method, aml_name_decl("PRR0", crs));
1493
1494    aml_append(method,
1495        aml_create_dword_field(aml_name("PRR0"), aml_int(5), "PRRI"));
1496
1497    if (is_piix4) {
1498        if_ctx = aml_if(aml_lless(aml_arg(0), aml_int(0x80)));
1499        aml_append(if_ctx, aml_store(aml_arg(0), aml_name("PRRI")));
1500        aml_append(method, if_ctx);
1501    } else {
1502        aml_append(method,
1503            aml_store(aml_and(aml_arg(0), aml_int(0xF), NULL),
1504                      aml_name("PRRI")));
1505    }
1506
1507    aml_append(method, aml_return(aml_name("PRR0")));
1508    return method;
1509}
1510
1511/* _STA method - get status */
1512static Aml *build_irq_status_method(void)
1513{
1514    Aml *if_ctx;
1515    Aml *method = aml_method("IQST", 1, AML_NOTSERIALIZED);
1516
1517    if_ctx = aml_if(aml_and(aml_int(0x80), aml_arg(0), NULL));
1518    aml_append(if_ctx, aml_return(aml_int(0x09)));
1519    aml_append(method, if_ctx);
1520    aml_append(method, aml_return(aml_int(0x0B)));
1521    return method;
1522}
1523
1524static void build_piix4_pci0_int(Aml *table)
1525{
1526    Aml *dev;
1527    Aml *crs;
1528    Aml *field;
1529    Aml *method;
1530    uint32_t irqs;
1531    Aml *sb_scope = aml_scope("_SB");
1532    Aml *pci0_scope = aml_scope("PCI0");
1533
1534    aml_append(pci0_scope, build_prt(true));
1535    aml_append(sb_scope, pci0_scope);
1536
1537    field = aml_field("PCI0.ISA.P40C", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
1538    aml_append(field, aml_named_field("PRQ0", 8));
1539    aml_append(field, aml_named_field("PRQ1", 8));
1540    aml_append(field, aml_named_field("PRQ2", 8));
1541    aml_append(field, aml_named_field("PRQ3", 8));
1542    aml_append(sb_scope, field);
1543
1544    aml_append(sb_scope, build_irq_status_method());
1545    aml_append(sb_scope, build_iqcr_method(true));
1546
1547    aml_append(sb_scope, build_link_dev("LNKA", 0, aml_name("PRQ0")));
1548    aml_append(sb_scope, build_link_dev("LNKB", 1, aml_name("PRQ1")));
1549    aml_append(sb_scope, build_link_dev("LNKC", 2, aml_name("PRQ2")));
1550    aml_append(sb_scope, build_link_dev("LNKD", 3, aml_name("PRQ3")));
1551
1552    dev = aml_device("LNKS");
1553    {
1554        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C0F")));
1555        aml_append(dev, aml_name_decl("_UID", aml_int(4)));
1556
1557        crs = aml_resource_template();
1558        irqs = 9;
1559        aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL,
1560                                      AML_ACTIVE_HIGH, AML_SHARED,
1561                                      &irqs, 1));
1562        aml_append(dev, aml_name_decl("_PRS", crs));
1563
1564        /* The SCI cannot be disabled and is always attached to GSI 9,
1565         * so these are no-ops.  We only need this link to override the
1566         * polarity to active high and match the content of the MADT.
1567         */
1568        method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1569        aml_append(method, aml_return(aml_int(0x0b)));
1570        aml_append(dev, method);
1571
1572        method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
1573        aml_append(dev, method);
1574
1575        method = aml_method("_CRS", 0, AML_NOTSERIALIZED);
1576        aml_append(method, aml_return(aml_name("_PRS")));
1577        aml_append(dev, method);
1578
1579        method = aml_method("_SRS", 1, AML_NOTSERIALIZED);
1580        aml_append(dev, method);
1581    }
1582    aml_append(sb_scope, dev);
1583
1584    aml_append(table, sb_scope);
1585}
1586
1587static void append_q35_prt_entry(Aml *ctx, uint32_t nr, const char *name)
1588{
1589    int i;
1590    int head;
1591    Aml *pkg;
1592    char base = name[3] < 'E' ? 'A' : 'E';
1593    char *s = g_strdup(name);
1594    Aml *a_nr = aml_int((nr << 16) | 0xffff);
1595
1596    assert(strlen(s) == 4);
1597
1598    head = name[3] - base;
1599    for (i = 0; i < 4; i++) {
1600        if (head + i > 3) {
1601            head = i * -1;
1602        }
1603        s[3] = base + head + i;
1604        pkg = aml_package(4);
1605        aml_append(pkg, a_nr);
1606        aml_append(pkg, aml_int(i));
1607        aml_append(pkg, aml_name("%s", s));
1608        aml_append(pkg, aml_int(0));
1609        aml_append(ctx, pkg);
1610    }
1611    g_free(s);
1612}
1613
1614static Aml *build_q35_routing_table(const char *str)
1615{
1616    int i;
1617    Aml *pkg;
1618    char *name = g_strdup_printf("%s ", str);
1619
1620    pkg = aml_package(128);
1621    for (i = 0; i < 0x18; i++) {
1622            name[3] = 'E' + (i & 0x3);
1623            append_q35_prt_entry(pkg, i, name);
1624    }
1625
1626    name[3] = 'E';
1627    append_q35_prt_entry(pkg, 0x18, name);
1628
1629    /* INTA -> PIRQA for slot 25 - 31, see the default value of D<N>IR */
1630    for (i = 0x0019; i < 0x1e; i++) {
1631        name[3] = 'A';
1632        append_q35_prt_entry(pkg, i, name);
1633    }
1634
1635    /* PCIe->PCI bridge. use PIRQ[E-H] */
1636    name[3] = 'E';
1637    append_q35_prt_entry(pkg, 0x1e, name);
1638    name[3] = 'A';
1639    append_q35_prt_entry(pkg, 0x1f, name);
1640
1641    g_free(name);
1642    return pkg;
1643}
1644
1645static void build_q35_pci0_int(Aml *table)
1646{
1647    Aml *field;
1648    Aml *method;
1649    Aml *sb_scope = aml_scope("_SB");
1650    Aml *pci0_scope = aml_scope("PCI0");
1651
1652    /* Zero => PIC mode, One => APIC Mode */
1653    aml_append(table, aml_name_decl("PICF", aml_int(0)));
1654    method = aml_method("_PIC", 1, AML_NOTSERIALIZED);
1655    {
1656        aml_append(method, aml_store(aml_arg(0), aml_name("PICF")));
1657    }
1658    aml_append(table, method);
1659
1660    aml_append(pci0_scope,
1661        aml_name_decl("PRTP", build_q35_routing_table("LNK")));
1662    aml_append(pci0_scope,
1663        aml_name_decl("PRTA", build_q35_routing_table("GSI")));
1664
1665    method = aml_method("_PRT", 0, AML_NOTSERIALIZED);
1666    {
1667        Aml *if_ctx;
1668        Aml *else_ctx;
1669
1670        /* PCI IRQ routing table, example from ACPI 2.0a specification,
1671           section 6.2.8.1 */
1672        /* Note: we provide the same info as the PCI routing
1673           table of the Bochs BIOS */
1674        if_ctx = aml_if(aml_equal(aml_name("PICF"), aml_int(0)));
1675        aml_append(if_ctx, aml_return(aml_name("PRTP")));
1676        aml_append(method, if_ctx);
1677        else_ctx = aml_else();
1678        aml_append(else_ctx, aml_return(aml_name("PRTA")));
1679        aml_append(method, else_ctx);
1680    }
1681    aml_append(pci0_scope, method);
1682    aml_append(sb_scope, pci0_scope);
1683
1684    field = aml_field("PCI0.ISA.PIRQ", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
1685    aml_append(field, aml_named_field("PRQA", 8));
1686    aml_append(field, aml_named_field("PRQB", 8));
1687    aml_append(field, aml_named_field("PRQC", 8));
1688    aml_append(field, aml_named_field("PRQD", 8));
1689    aml_append(field, aml_reserved_field(0x20));
1690    aml_append(field, aml_named_field("PRQE", 8));
1691    aml_append(field, aml_named_field("PRQF", 8));
1692    aml_append(field, aml_named_field("PRQG", 8));
1693    aml_append(field, aml_named_field("PRQH", 8));
1694    aml_append(sb_scope, field);
1695
1696    aml_append(sb_scope, build_irq_status_method());
1697    aml_append(sb_scope, build_iqcr_method(false));
1698
1699    aml_append(sb_scope, build_link_dev("LNKA", 0, aml_name("PRQA")));
1700    aml_append(sb_scope, build_link_dev("LNKB", 1, aml_name("PRQB")));
1701    aml_append(sb_scope, build_link_dev("LNKC", 2, aml_name("PRQC")));
1702    aml_append(sb_scope, build_link_dev("LNKD", 3, aml_name("PRQD")));
1703    aml_append(sb_scope, build_link_dev("LNKE", 4, aml_name("PRQE")));
1704    aml_append(sb_scope, build_link_dev("LNKF", 5, aml_name("PRQF")));
1705    aml_append(sb_scope, build_link_dev("LNKG", 6, aml_name("PRQG")));
1706    aml_append(sb_scope, build_link_dev("LNKH", 7, aml_name("PRQH")));
1707
1708    aml_append(sb_scope, build_gsi_link_dev("GSIA", 0x10, 0x10));
1709    aml_append(sb_scope, build_gsi_link_dev("GSIB", 0x11, 0x11));
1710    aml_append(sb_scope, build_gsi_link_dev("GSIC", 0x12, 0x12));
1711    aml_append(sb_scope, build_gsi_link_dev("GSID", 0x13, 0x13));
1712    aml_append(sb_scope, build_gsi_link_dev("GSIE", 0x14, 0x14));
1713    aml_append(sb_scope, build_gsi_link_dev("GSIF", 0x15, 0x15));
1714    aml_append(sb_scope, build_gsi_link_dev("GSIG", 0x16, 0x16));
1715    aml_append(sb_scope, build_gsi_link_dev("GSIH", 0x17, 0x17));
1716
1717    aml_append(table, sb_scope);
1718}
1719
1720static void build_q35_isa_bridge(Aml *table)
1721{
1722    Aml *dev;
1723    Aml *scope;
1724    Aml *field;
1725
1726    scope =  aml_scope("_SB.PCI0");
1727    dev = aml_device("ISA");
1728    aml_append(dev, aml_name_decl("_ADR", aml_int(0x001F0000)));
1729
1730    /* ICH9 PCI to ISA irq remapping */
1731    aml_append(dev, aml_operation_region("PIRQ", AML_PCI_CONFIG,
1732                                         aml_int(0x60), 0x0C));
1733
1734    aml_append(dev, aml_operation_region("LPCD", AML_PCI_CONFIG,
1735                                         aml_int(0x80), 0x02));
1736    field = aml_field("LPCD", AML_ANY_ACC, AML_NOLOCK, AML_PRESERVE);
1737    aml_append(field, aml_named_field("COMA", 3));
1738    aml_append(field, aml_reserved_field(1));
1739    aml_append(field, aml_named_field("COMB", 3));
1740    aml_append(field, aml_reserved_field(1));
1741    aml_append(field, aml_named_field("LPTD", 2));
1742    aml_append(dev, field);
1743
1744    aml_append(dev, aml_operation_region("LPCE", AML_PCI_CONFIG,
1745                                         aml_int(0x82), 0x02));
1746    /* enable bits */
1747    field = aml_field("LPCE", AML_ANY_ACC, AML_NOLOCK, AML_PRESERVE);
1748    aml_append(field, aml_named_field("CAEN", 1));
1749    aml_append(field, aml_named_field("CBEN", 1));
1750    aml_append(field, aml_named_field("LPEN", 1));
1751    aml_append(dev, field);
1752
1753    aml_append(scope, dev);
1754    aml_append(table, scope);
1755}
1756
1757static void build_piix4_pm(Aml *table)
1758{
1759    Aml *dev;
1760    Aml *scope;
1761
1762    scope =  aml_scope("_SB.PCI0");
1763    dev = aml_device("PX13");
1764    aml_append(dev, aml_name_decl("_ADR", aml_int(0x00010003)));
1765
1766    aml_append(dev, aml_operation_region("P13C", AML_PCI_CONFIG,
1767                                         aml_int(0x00), 0xff));
1768    aml_append(scope, dev);
1769    aml_append(table, scope);
1770}
1771
1772static void build_piix4_isa_bridge(Aml *table)
1773{
1774    Aml *dev;
1775    Aml *scope;
1776    Aml *field;
1777
1778    scope =  aml_scope("_SB.PCI0");
1779    dev = aml_device("ISA");
1780    aml_append(dev, aml_name_decl("_ADR", aml_int(0x00010000)));
1781
1782    /* PIIX PCI to ISA irq remapping */
1783    aml_append(dev, aml_operation_region("P40C", AML_PCI_CONFIG,
1784                                         aml_int(0x60), 0x04));
1785    /* enable bits */
1786    field = aml_field("^PX13.P13C", AML_ANY_ACC, AML_NOLOCK, AML_PRESERVE);
1787    /* Offset(0x5f),, 7, */
1788    aml_append(field, aml_reserved_field(0x2f8));
1789    aml_append(field, aml_reserved_field(7));
1790    aml_append(field, aml_named_field("LPEN", 1));
1791    /* Offset(0x67),, 3, */
1792    aml_append(field, aml_reserved_field(0x38));
1793    aml_append(field, aml_reserved_field(3));
1794    aml_append(field, aml_named_field("CAEN", 1));
1795    aml_append(field, aml_reserved_field(3));
1796    aml_append(field, aml_named_field("CBEN", 1));
1797    aml_append(dev, field);
1798
1799    aml_append(scope, dev);
1800    aml_append(table, scope);
1801}
1802
1803static void build_piix4_pci_hotplug(Aml *table)
1804{
1805    Aml *scope;
1806    Aml *field;
1807    Aml *method;
1808
1809    scope =  aml_scope("_SB.PCI0");
1810
1811    aml_append(scope,
1812        aml_operation_region("PCST", AML_SYSTEM_IO, aml_int(0xae00), 0x08));
1813    field = aml_field("PCST", AML_DWORD_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
1814    aml_append(field, aml_named_field("PCIU", 32));
1815    aml_append(field, aml_named_field("PCID", 32));
1816    aml_append(scope, field);
1817
1818    aml_append(scope,
1819        aml_operation_region("SEJ", AML_SYSTEM_IO, aml_int(0xae08), 0x04));
1820    field = aml_field("SEJ", AML_DWORD_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
1821    aml_append(field, aml_named_field("B0EJ", 32));
1822    aml_append(scope, field);
1823
1824    aml_append(scope,
1825        aml_operation_region("BNMR", AML_SYSTEM_IO, aml_int(0xae10), 0x04));
1826    field = aml_field("BNMR", AML_DWORD_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
1827    aml_append(field, aml_named_field("BNUM", 32));
1828    aml_append(scope, field);
1829
1830    aml_append(scope, aml_mutex("BLCK", 0));
1831
1832    method = aml_method("PCEJ", 2, AML_NOTSERIALIZED);
1833    aml_append(method, aml_acquire(aml_name("BLCK"), 0xFFFF));
1834    aml_append(method, aml_store(aml_arg(0), aml_name("BNUM")));
1835    aml_append(method,
1836        aml_store(aml_shiftleft(aml_int(1), aml_arg(1)), aml_name("B0EJ")));
1837    aml_append(method, aml_release(aml_name("BLCK")));
1838    aml_append(method, aml_return(aml_int(0)));
1839    aml_append(scope, method);
1840
1841    aml_append(table, scope);
1842}
1843
1844static Aml *build_q35_osc_method(void)
1845{
1846    Aml *if_ctx;
1847    Aml *if_ctx2;
1848    Aml *else_ctx;
1849    Aml *method;
1850    Aml *a_cwd1 = aml_name("CDW1");
1851    Aml *a_ctrl = aml_local(0);
1852
1853    method = aml_method("_OSC", 4, AML_NOTSERIALIZED);
1854    aml_append(method, aml_create_dword_field(aml_arg(3), aml_int(0), "CDW1"));
1855
1856    if_ctx = aml_if(aml_equal(
1857        aml_arg(0), aml_touuid("33DB4D5B-1FF7-401C-9657-7441C03DD766")));
1858    aml_append(if_ctx, aml_create_dword_field(aml_arg(3), aml_int(4), "CDW2"));
1859    aml_append(if_ctx, aml_create_dword_field(aml_arg(3), aml_int(8), "CDW3"));
1860
1861    aml_append(if_ctx, aml_store(aml_name("CDW3"), a_ctrl));
1862
1863    /*
1864     * Always allow native PME, AER (no dependencies)
1865     * Allow SHPC (PCI bridges can have SHPC controller)
1866     */
1867    aml_append(if_ctx, aml_and(a_ctrl, aml_int(0x1F), a_ctrl));
1868
1869    if_ctx2 = aml_if(aml_lnot(aml_equal(aml_arg(1), aml_int(1))));
1870    /* Unknown revision */
1871    aml_append(if_ctx2, aml_or(a_cwd1, aml_int(0x08), a_cwd1));
1872    aml_append(if_ctx, if_ctx2);
1873
1874    if_ctx2 = aml_if(aml_lnot(aml_equal(aml_name("CDW3"), a_ctrl)));
1875    /* Capabilities bits were masked */
1876    aml_append(if_ctx2, aml_or(a_cwd1, aml_int(0x10), a_cwd1));
1877    aml_append(if_ctx, if_ctx2);
1878
1879    /* Update DWORD3 in the buffer */
1880    aml_append(if_ctx, aml_store(a_ctrl, aml_name("CDW3")));
1881    aml_append(method, if_ctx);
1882
1883    else_ctx = aml_else();
1884    /* Unrecognized UUID */
1885    aml_append(else_ctx, aml_or(a_cwd1, aml_int(4), a_cwd1));
1886    aml_append(method, else_ctx);
1887
1888    aml_append(method, aml_return(aml_arg(3)));
1889    return method;
1890}
1891
1892static void
1893build_dsdt(GArray *table_data, BIOSLinker *linker,
1894           AcpiPmInfo *pm, AcpiMiscInfo *misc,
1895           Range *pci_hole, Range *pci_hole64, MachineState *machine)
1896{
1897    CrsRangeEntry *entry;
1898    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;
1899    CrsRangeSet crs_range_set;
1900    PCMachineState *pcms = PC_MACHINE(machine);
1901    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(machine);
1902    uint32_t nr_mem = machine->ram_slots;
1903    int root_bus_limit = 0xFF;
1904    PCIBus *bus = NULL;
1905    int i;
1906
1907    dsdt = init_aml_allocator();
1908
1909    /* Reserve space for header */
1910    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));
1911
1912    build_dbg_aml(dsdt);
1913    if (misc->is_piix4) {
1914        sb_scope = aml_scope("_SB");
1915        dev = aml_device("PCI0");
1916        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));
1917        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));
1918        aml_append(dev, aml_name_decl("_UID", aml_int(1)));
1919        aml_append(sb_scope, dev);
1920        aml_append(dsdt, sb_scope);
1921
1922        build_hpet_aml(dsdt);
1923        build_piix4_pm(dsdt);
1924        build_piix4_isa_bridge(dsdt);
1925        build_isa_devices_aml(dsdt);
1926        build_piix4_pci_hotplug(dsdt);
1927        build_piix4_pci0_int(dsdt);
1928    } else {
1929        sb_scope = aml_scope("_SB");
1930        dev = aml_device("PCI0");
1931        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));
1932        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));
1933        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));
1934        aml_append(dev, aml_name_decl("_UID", aml_int(1)));
1935        aml_append(dev, build_q35_osc_method());
1936        aml_append(sb_scope, dev);
1937        aml_append(dsdt, sb_scope);
1938
1939        build_hpet_aml(dsdt);
1940        build_q35_isa_bridge(dsdt);
1941        build_isa_devices_aml(dsdt);
1942        build_q35_pci0_int(dsdt);
1943    }
1944
1945    if (pcmc->legacy_cpu_hotplug) {
1946        build_legacy_cpu_hotplug_aml(dsdt, machine, pm->cpu_hp_io_base);
1947    } else {
1948        CPUHotplugFeatures opts = {
1949            .apci_1_compatible = true, .has_legacy_cphp = true
1950        };
1951        build_cpus_aml(dsdt, machine, opts, pm->cpu_hp_io_base,
1952                       "\\_SB.PCI0", "\\_GPE._E02");
1953    }
1954    build_memory_hotplug_aml(dsdt, nr_mem, "\\_SB.PCI0", "\\_GPE._E03");
1955
1956    scope =  aml_scope("_GPE");
1957    {
1958        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));
1959
1960        if (misc->is_piix4) {
1961            method = aml_method("_E01", 0, AML_NOTSERIALIZED);
1962            aml_append(method,
1963                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));
1964            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));
1965            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));
1966            aml_append(scope, method);
1967        }
1968
1969        if (pcms->acpi_nvdimm_state.is_enabled) {
1970            method = aml_method("_E04", 0, AML_NOTSERIALIZED);
1971            aml_append(method, aml_notify(aml_name("\\_SB.NVDR"),
1972                                          aml_int(0x80)));
1973            aml_append(scope, method);
1974        }
1975    }
1976    aml_append(dsdt, scope);
1977
1978    crs_range_set_init(&crs_range_set);
1979    bus = PC_MACHINE(machine)->bus;
1980    if (bus) {
1981        QLIST_FOREACH(bus, &bus->child, sibling) {
1982            uint8_t bus_num = pci_bus_num(bus);
1983            uint8_t numa_node = pci_bus_numa_node(bus);
1984
1985            /* look only for expander root buses */
1986            if (!pci_bus_is_root(bus)) {
1987                continue;
1988            }
1989
1990            if (bus_num < root_bus_limit) {
1991                root_bus_limit = bus_num - 1;
1992            }
1993
1994            scope = aml_scope("\\_SB");
1995            dev = aml_device("PC%.02X", bus_num);
1996            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));
1997            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));
1998            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));
1999            if (pci_bus_is_express(bus)) {
2000                aml_append(dev, build_q35_osc_method());
2001            }
2002
2003            if (numa_node != NUMA_NODE_UNASSIGNED) {
2004                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));
2005            }
2006
2007            aml_append(dev, build_prt(false));
2008            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent), &crs_range_set);
2009            aml_append(dev, aml_name_decl("_CRS", crs));
2010            aml_append(scope, dev);
2011            aml_append(dsdt, scope);
2012        }
2013    }
2014
2015    scope = aml_scope("\\_SB.PCI0");
2016    /* build PCI0._CRS */
2017    crs = aml_resource_template();
2018    aml_append(crs,
2019        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,
2020                            0x0000, 0x0, root_bus_limit,
2021                            0x0000, root_bus_limit + 1));
2022    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));
2023
2024    aml_append(crs,
2025        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
2026                    AML_POS_DECODE, AML_ENTIRE_RANGE,
2027                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));
2028
2029    crs_replace_with_free_ranges(crs_range_set.io_ranges, 0x0D00, 0xFFFF);
2030    for (i = 0; i < crs_range_set.io_ranges->len; i++) {
2031        entry = g_ptr_array_index(crs_range_set.io_ranges, i);
2032        aml_append(crs,
2033            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
2034                        AML_POS_DECODE, AML_ENTIRE_RANGE,
2035                        0x0000, entry->base, entry->limit,
2036                        0x0000, entry->limit - entry->base + 1));
2037    }
2038
2039    aml_append(crs,
2040        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
2041                         AML_CACHEABLE, AML_READ_WRITE,
2042                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));
2043
2044    crs_replace_with_free_ranges(crs_range_set.mem_ranges,
2045                                 range_lob(pci_hole),
2046                                 range_upb(pci_hole));
2047    for (i = 0; i < crs_range_set.mem_ranges->len; i++) {
2048        entry = g_ptr_array_index(crs_range_set.mem_ranges, i);
2049        aml_append(crs,
2050            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
2051                             AML_NON_CACHEABLE, AML_READ_WRITE,
2052                             0, entry->base, entry->limit,
2053                             0, entry->limit - entry->base + 1));
2054    }
2055
2056    if (!range_is_empty(pci_hole64)) {
2057        crs_replace_with_free_ranges(crs_range_set.mem_64bit_ranges,
2058                                     range_lob(pci_hole64),
2059                                     range_upb(pci_hole64));
2060        for (i = 0; i < crs_range_set.mem_64bit_ranges->len; i++) {
2061            entry = g_ptr_array_index(crs_range_set.mem_64bit_ranges, i);
2062            aml_append(crs,
2063                       aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED,
2064                                        AML_MAX_FIXED,
2065                                        AML_CACHEABLE, AML_READ_WRITE,
2066                                        0, entry->base, entry->limit,
2067                                        0, entry->limit - entry->base + 1));
2068        }
2069    }
2070
2071    if (misc->tpm_version != TPM_VERSION_UNSPEC) {
2072        aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,
2073                   TPM_TIS_ADDR_SIZE, AML_READ_WRITE));
2074    }
2075    aml_append(scope, aml_name_decl("_CRS", crs));
2076
2077    /* reserve GPE0 block resources */
2078    dev = aml_device("GPE0");
2079    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));
2080    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));
2081    /* device present, functioning, decoding, not shown in UI */
2082    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
2083    crs = aml_resource_template();
2084    aml_append(crs,
2085        aml_io(AML_DECODE16, pm->gpe0_blk, pm->gpe0_blk, 1, pm->gpe0_blk_len)
2086    );
2087    aml_append(dev, aml_name_decl("_CRS", crs));
2088    aml_append(scope, dev);
2089
2090    crs_range_set_free(&crs_range_set);
2091
2092    /* reserve PCIHP resources */
2093    if (pm->pcihp_io_len) {
2094        dev = aml_device("PHPR");
2095        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));
2096        aml_append(dev,
2097            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));
2098        /* device present, functioning, decoding, not shown in UI */
2099        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
2100        crs = aml_resource_template();
2101        aml_append(crs,
2102            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,
2103                   pm->pcihp_io_len)
2104        );
2105        aml_append(dev, aml_name_decl("_CRS", crs));
2106        aml_append(scope, dev);
2107    }
2108    aml_append(dsdt, scope);
2109
2110    /*  create S3_ / S4_ / S5_ packages if necessary */
2111    scope = aml_scope("\\");
2112    if (!pm->s3_disabled) {
2113        pkg = aml_package(4);
2114        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */
2115        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */
2116        aml_append(pkg, aml_int(0)); /* reserved */
2117        aml_append(pkg, aml_int(0)); /* reserved */
2118        aml_append(scope, aml_name_decl("_S3", pkg));
2119    }
2120
2121    if (!pm->s4_disabled) {
2122        pkg = aml_package(4);
2123        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */
2124        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */
2125        aml_append(pkg, aml_int(pm->s4_val));
2126        aml_append(pkg, aml_int(0)); /* reserved */
2127        aml_append(pkg, aml_int(0)); /* reserved */
2128        aml_append(scope, aml_name_decl("_S4", pkg));
2129    }
2130
2131    pkg = aml_package(4);
2132    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */
2133    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */
2134    aml_append(pkg, aml_int(0)); /* reserved */
2135    aml_append(pkg, aml_int(0)); /* reserved */
2136    aml_append(scope, aml_name_decl("_S5", pkg));
2137    aml_append(dsdt, scope);
2138
2139    /* create fw_cfg node, unconditionally */
2140    {
2141        /* when using port i/o, the 8-bit data register *always* overlaps
2142         * with half of the 16-bit control register. Hence, the total size
2143         * of the i/o region used is FW_CFG_CTL_SIZE; when using DMA, the
2144         * DMA control register is located at FW_CFG_DMA_IO_BASE + 4 */
2145        uint8_t io_size = object_property_get_bool(OBJECT(pcms->fw_cfg),
2146                                                   "dma_enabled", NULL) ?
2147                          ROUND_UP(FW_CFG_CTL_SIZE, 4) + sizeof(dma_addr_t) :
2148                          FW_CFG_CTL_SIZE;
2149
2150        scope = aml_scope("\\_SB.PCI0");
2151        dev = aml_device("FWCF");
2152
2153        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0002")));
2154
2155        /* device present, functioning, decoding, not shown in UI */
2156        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
2157
2158        crs = aml_resource_template();
2159        aml_append(crs,
2160            aml_io(AML_DECODE16, FW_CFG_IO_BASE, FW_CFG_IO_BASE, 0x01, io_size)
2161        );
2162        aml_append(dev, aml_name_decl("_CRS", crs));
2163
2164        aml_append(scope, dev);
2165        aml_append(dsdt, scope);
2166    }
2167
2168    if (misc->applesmc_io_base) {
2169        scope = aml_scope("\\_SB.PCI0.ISA");
2170        dev = aml_device("SMC");
2171
2172        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));
2173        /* device present, functioning, decoding, not shown in UI */
2174        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
2175
2176        crs = aml_resource_template();
2177        aml_append(crs,
2178            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,
2179                   0x01, APPLESMC_MAX_DATA_LENGTH)
2180        );
2181        aml_append(crs, aml_irq_no_flags(6));
2182        aml_append(dev, aml_name_decl("_CRS", crs));
2183
2184        aml_append(scope, dev);
2185        aml_append(dsdt, scope);
2186    }
2187
2188    if (misc->pvpanic_port) {
2189        scope = aml_scope("\\_SB.PCI0.ISA");
2190
2191        dev = aml_device("PEVT");
2192        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));
2193
2194        crs = aml_resource_template();
2195        aml_append(crs,
2196            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)
2197        );
2198        aml_append(dev, aml_name_decl("_CRS", crs));
2199
2200        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,
2201                                              aml_int(misc->pvpanic_port), 1));
2202        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
2203        aml_append(field, aml_named_field("PEPT", 8));
2204        aml_append(dev, field);
2205
2206        /* device present, functioning, decoding, shown in UI */
2207        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
2208
2209        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);
2210        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));
2211        aml_append(method, aml_return(aml_local(0)));
2212        aml_append(dev, method);
2213
2214        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);
2215        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));
2216        aml_append(dev, method);
2217
2218        aml_append(scope, dev);
2219        aml_append(dsdt, scope);
2220    }
2221
2222    sb_scope = aml_scope("\\_SB");
2223    {
2224        Object *pci_host;
2225        PCIBus *bus = NULL;
2226
2227        pci_host = acpi_get_i386_pci_host();
2228        if (pci_host) {
2229            bus = PCI_HOST_BRIDGE(pci_host)->bus;
2230        }
2231
2232        if (bus) {
2233            Aml *scope = aml_scope("PCI0");
2234            /* Scan all PCI buses. Generate tables to support hotplug. */
2235            build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);
2236
2237            if (misc->tpm_version != TPM_VERSION_UNSPEC) {
2238                dev = aml_device("ISA.TPM");
2239                aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));
2240                aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
2241                crs = aml_resource_template();
2242                aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,
2243                           TPM_TIS_ADDR_SIZE, AML_READ_WRITE));
2244                /*
2245                    FIXME: TPM_TIS_IRQ=5 conflicts with PNP0C0F irqs,
2246                    Rewrite to take IRQ from TPM device model and
2247                    fix default IRQ value there to use some unused IRQ
2248                 */
2249                /* aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ)); */
2250                aml_append(dev, aml_name_decl("_CRS", crs));
2251                aml_append(scope, dev);
2252            }
2253
2254            aml_append(sb_scope, scope);
2255        }
2256    }
2257    aml_append(dsdt, sb_scope);
2258
2259    /* copy AML table into ACPI tables blob and patch header there */
2260    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);
2261    build_header(linker, table_data,
2262        (void *)(table_data->data + table_data->len - dsdt->buf->len),
2263        "DSDT", dsdt->buf->len, 1, NULL, NULL);
2264    free_aml_allocator();
2265}
2266
2267static void
2268build_hpet(GArray *table_data, BIOSLinker *linker)
2269{
2270    Acpi20Hpet *hpet;
2271
2272    hpet = acpi_data_push(table_data, sizeof(*hpet));
2273    /* Note timer_block_id value must be kept in sync with value advertised by
2274     * emulated hpet
2275     */
2276    hpet->timer_block_id = cpu_to_le32(0x8086a201);
2277    hpet->addr.address = cpu_to_le64(HPET_BASE);
2278    build_header(linker, table_data,
2279                 (void *)hpet, "HPET", sizeof(*hpet), 1, NULL, NULL);
2280}
2281
2282static void
2283build_tpm_tcpa(GArray *table_data, BIOSLinker *linker, GArray *tcpalog)
2284{
2285    Acpi20Tcpa *tcpa = acpi_data_push(table_data, sizeof *tcpa);
2286    unsigned log_addr_size = sizeof(tcpa->log_area_start_address);
2287    unsigned log_addr_offset =
2288        (char *)&tcpa->log_area_start_address - table_data->data;
2289
2290    tcpa->platform_class = cpu_to_le16(TPM_TCPA_ACPI_CLASS_CLIENT);
2291    tcpa->log_area_minimum_length = cpu_to_le32(TPM_LOG_AREA_MINIMUM_SIZE);
2292    acpi_data_push(tcpalog, le32_to_cpu(tcpa->log_area_minimum_length));
2293
2294    bios_linker_loader_alloc(linker, ACPI_BUILD_TPMLOG_FILE, tcpalog, 1,
2295                             false /* high memory */);
2296
2297    /* log area start address to be filled by Guest linker */
2298    bios_linker_loader_add_pointer(linker,
2299        ACPI_BUILD_TABLE_FILE, log_addr_offset, log_addr_size,
2300        ACPI_BUILD_TPMLOG_FILE, 0);
2301
2302    build_header(linker, table_data,
2303                 (void *)tcpa, "TCPA", sizeof(*tcpa), 2, NULL, NULL);
2304}
2305
2306static void
2307build_tpm2(GArray *table_data, BIOSLinker *linker)
2308{
2309    Acpi20TPM2 *tpm2_ptr;
2310
2311    tpm2_ptr = acpi_data_push(table_data, sizeof *tpm2_ptr);
2312
2313    tpm2_ptr->platform_class = cpu_to_le16(TPM2_ACPI_CLASS_CLIENT);
2314    tpm2_ptr->control_area_address = cpu_to_le64(0);
2315    tpm2_ptr->start_method = cpu_to_le32(TPM2_START_METHOD_MMIO);
2316
2317    build_header(linker, table_data,
2318                 (void *)tpm2_ptr, "TPM2", sizeof(*tpm2_ptr), 4, NULL, NULL);
2319}
2320
2321static void
2322build_srat(GArray *table_data, BIOSLinker *linker, MachineState *machine)
2323{
2324    AcpiSystemResourceAffinityTable *srat;
2325    AcpiSratMemoryAffinity *numamem;
2326
2327    int i;
2328    int srat_start, numa_start, slots;
2329    uint64_t mem_len, mem_base, next_base;
2330    MachineClass *mc = MACHINE_GET_CLASS(machine);
2331    const CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);
2332    PCMachineState *pcms = PC_MACHINE(machine);
2333    ram_addr_t hotplugabble_address_space_size =
2334        object_property_get_int(OBJECT(pcms), PC_MACHINE_MEMHP_REGION_SIZE,
2335                                NULL);
2336
2337    srat_start = table_data->len;
2338
2339    srat = acpi_data_push(table_data, sizeof *srat);
2340    srat->reserved1 = cpu_to_le32(1);
2341
2342    for (i = 0; i < apic_ids->len; i++) {
2343        int node_id = apic_ids->cpus[i].props.node_id;
2344        uint32_t apic_id = apic_ids->cpus[i].arch_id;
2345
2346        if (apic_id < 255) {
2347            AcpiSratProcessorAffinity *core;
2348
2349            core = acpi_data_push(table_data, sizeof *core);
2350            core->type = ACPI_SRAT_PROCESSOR_APIC;
2351            core->length = sizeof(*core);
2352            core->local_apic_id = apic_id;
2353            core->proximity_lo = node_id;
2354            memset(core->proximity_hi, 0, 3);
2355            core->local_sapic_eid = 0;
2356            core->flags = cpu_to_le32(1);
2357        } else {
2358            AcpiSratProcessorX2ApicAffinity *core;
2359
2360            core = acpi_data_push(table_data, sizeof *core);
2361            core->type = ACPI_SRAT_PROCESSOR_x2APIC;
2362            core->length = sizeof(*core);
2363            core->x2apic_id = cpu_to_le32(apic_id);
2364            core->proximity_domain = cpu_to_le32(node_id);
2365            core->flags = cpu_to_le32(1);
2366        }
2367    }
2368
2369
2370    /* the memory map is a bit tricky, it contains at least one hole
2371     * from 640k-1M and possibly another one from 3.5G-4G.
2372     */
2373    next_base = 0;
2374    numa_start = table_data->len;
2375
2376    numamem = acpi_data_push(table_data, sizeof *numamem);
2377    build_srat_memory(numamem, 0, 640 * 1024, 0, MEM_AFFINITY_ENABLED);
2378    next_base = 1024 * 1024;
2379    for (i = 1; i < pcms->numa_nodes + 1; ++i) {
2380        mem_base = next_base;
2381        mem_len = pcms->node_mem[i - 1];
2382        if (i == 1) {
2383            mem_len -= 1024 * 1024;
2384        }
2385        next_base = mem_base + mem_len;
2386
2387        /* Cut out the ACPI_PCI hole */
2388        if (mem_base <= pcms->below_4g_mem_size &&
2389            next_base > pcms->below_4g_mem_size) {
2390            mem_len -= next_base - pcms->below_4g_mem_size;
2391            if (mem_len > 0) {
2392                numamem = acpi_data_push(table_data, sizeof *numamem);
2393                build_srat_memory(numamem, mem_base, mem_len, i - 1,
2394                                  MEM_AFFINITY_ENABLED);
2395            }
2396            mem_base = 1ULL << 32;
2397            mem_len = next_base - pcms->below_4g_mem_size;
2398            next_base += (1ULL << 32) - pcms->below_4g_mem_size;
2399        }
2400        numamem = acpi_data_push(table_data, sizeof *numamem);
2401        build_srat_memory(numamem, mem_base, mem_len, i - 1,
2402                          MEM_AFFINITY_ENABLED);
2403    }
2404    slots = (table_data->len - numa_start) / sizeof *numamem;
2405    for (; slots < pcms->numa_nodes + 2; slots++) {
2406        numamem = acpi_data_push(table_data, sizeof *numamem);
2407        build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS);
2408    }
2409
2410    /*
2411     * Entry is required for Windows to enable memory hotplug in OS
2412     * and for Linux to enable SWIOTLB when booted with less than
2413     * 4G of RAM. Windows works better if the entry sets proximity
2414     * to the highest NUMA node in the machine.
2415     * Memory devices may override proximity set by this entry,
2416     * providing _PXM method if necessary.
2417     */
2418    if (hotplugabble_address_space_size) {
2419        numamem = acpi_data_push(table_data, sizeof *numamem);
2420        build_srat_memory(numamem, pcms->hotplug_memory.base,
2421                          hotplugabble_address_space_size, pcms->numa_nodes - 1,
2422                          MEM_AFFINITY_HOTPLUGGABLE | MEM_AFFINITY_ENABLED);
2423    }
2424
2425    build_header(linker, table_data,
2426                 (void *)(table_data->data + srat_start),
2427                 "SRAT",
2428                 table_data->len - srat_start, 1, NULL, NULL);
2429}
2430
2431static void
2432build_mcfg_q35(GArray *table_data, BIOSLinker *linker, AcpiMcfgInfo *info)
2433{
2434    AcpiTableMcfg *mcfg;
2435    const char *sig;
2436    int len = sizeof(*mcfg) + 1 * sizeof(mcfg->allocation[0]);
2437
2438    mcfg = acpi_data_push(table_data, len);
2439    mcfg->allocation[0].address = cpu_to_le64(info->mcfg_base);
2440    /* Only a single allocation so no need to play with segments */
2441    mcfg->allocation[0].pci_segment = cpu_to_le16(0);
2442    mcfg->allocation[0].start_bus_number = 0;
2443    mcfg->allocation[0].end_bus_number = PCIE_MMCFG_BUS(info->mcfg_size - 1);
2444
2445    /* MCFG is used for ECAM which can be enabled or disabled by guest.
2446     * To avoid table size changes (which create migration issues),
2447     * always create the table even if there are no allocations,
2448     * but set the signature to a reserved value in this case.
2449     * ACPI spec requires OSPMs to ignore such tables.
2450     */
2451    if (info->mcfg_base == PCIE_BASE_ADDR_UNMAPPED) {
2452        /* Reserved signature: ignored by OSPM */
2453        sig = "QEMU";
2454    } else {
2455        sig = "MCFG";
2456    }
2457    build_header(linker, table_data, (void *)mcfg, sig, len, 1, NULL, NULL);
2458}
2459
2460/*
2461 * VT-d spec 8.1 DMA Remapping Reporting Structure
2462 * (version Oct. 2014 or later)
2463 */
2464static void
2465build_dmar_q35(GArray *table_data, BIOSLinker *linker)
2466{
2467    int dmar_start = table_data->len;
2468
2469    AcpiTableDmar *dmar;
2470    AcpiDmarHardwareUnit *drhd;
2471    AcpiDmarRootPortATS *atsr;
2472    uint8_t dmar_flags = 0;
2473    X86IOMMUState *iommu = x86_iommu_get_default();
2474    AcpiDmarDeviceScope *scope = NULL;
2475    /* Root complex IOAPIC use one path[0] only */
2476    size_t ioapic_scope_size = sizeof(*scope) + sizeof(scope->path[0]);
2477
2478    assert(iommu);
2479    if (iommu->intr_supported) {
2480        dmar_flags |= 0x1;      /* Flags: 0x1: INT_REMAP */
2481    }
2482
2483    dmar = acpi_data_push(table_data, sizeof(*dmar));
2484    dmar->host_address_width = VTD_HOST_ADDRESS_WIDTH - 1;
2485    dmar->flags = dmar_flags;
2486
2487    /* DMAR Remapping Hardware Unit Definition structure */
2488    drhd = acpi_data_push(table_data, sizeof(*drhd) + ioapic_scope_size);
2489    drhd->type = cpu_to_le16(ACPI_DMAR_TYPE_HARDWARE_UNIT);
2490    drhd->length = cpu_to_le16(sizeof(*drhd) + ioapic_scope_size);
2491    drhd->flags = ACPI_DMAR_INCLUDE_PCI_ALL;
2492    drhd->pci_segment = cpu_to_le16(0);
2493    drhd->address = cpu_to_le64(Q35_HOST_BRIDGE_IOMMU_ADDR);
2494
2495    /* Scope definition for the root-complex IOAPIC. See VT-d spec
2496     * 8.3.1 (version Oct. 2014 or later). */
2497    scope = &drhd->scope[0];
2498    scope->entry_type = 0x03;   /* Type: 0x03 for IOAPIC */
2499    scope->length = ioapic_scope_size;
2500    scope->enumeration_id = ACPI_BUILD_IOAPIC_ID;
2501    scope->bus = Q35_PSEUDO_BUS_PLATFORM;
2502    scope->path[0].device = PCI_SLOT(Q35_PSEUDO_DEVFN_IOAPIC);
2503    scope->path[0].function = PCI_FUNC(Q35_PSEUDO_DEVFN_IOAPIC);
2504
2505    if (iommu->dt_supported) {
2506        atsr = acpi_data_push(table_data, sizeof(*atsr));
2507        atsr->type = cpu_to_le16(ACPI_DMAR_TYPE_ATSR);
2508        atsr->length = cpu_to_le16(sizeof(*atsr));
2509        atsr->flags = ACPI_DMAR_ATSR_ALL_PORTS;
2510        atsr->pci_segment = cpu_to_le16(0);
2511    }
2512
2513    build_header(linker, table_data, (void *)(table_data->data + dmar_start),
2514                 "DMAR", table_data->len - dmar_start, 1, NULL, NULL);
2515}
2516/*
2517 *   IVRS table as specified in AMD IOMMU Specification v2.62, Section 5.2
2518 *   accessible here http://support.amd.com/TechDocs/48882_IOMMU.pdf
2519 */
2520static void
2521build_amd_iommu(GArray *table_data, BIOSLinker *linker)
2522{
2523    int iommu_start = table_data->len;
2524    AMDVIState *s = AMD_IOMMU_DEVICE(x86_iommu_get_default());
2525
2526    /* IVRS header */
2527    acpi_data_push(table_data, sizeof(AcpiTableHeader));
2528    /* IVinfo - IO virtualization information common to all
2529     * IOMMU units in a system
2530     */
2531    build_append_int_noprefix(table_data, 40UL << 8/* PASize */, 4);
2532    /* reserved */
2533    build_append_int_noprefix(table_data, 0, 8);
2534
2535    /* IVHD definition - type 10h */
2536    build_append_int_noprefix(table_data, 0x10, 1);
2537    /* virtualization flags */
2538    build_append_int_noprefix(table_data,
2539                             (1UL << 0) | /* HtTunEn      */
2540                             (1UL << 4) | /* iotblSup     */
2541                             (1UL << 6) | /* PrefSup      */
2542                             (1UL << 7),  /* PPRSup       */
2543                             1);
2544    /* IVHD length */
2545    build_append_int_noprefix(table_data, 0x24, 2);
2546    /* DeviceID */
2547    build_append_int_noprefix(table_data, s->devid, 2);
2548    /* Capability offset */
2549    build_append_int_noprefix(table_data, s->capab_offset, 2);
2550    /* IOMMU base address */
2551    build_append_int_noprefix(table_data, s->mmio.addr, 8);
2552    /* PCI Segment Group */
2553    build_append_int_noprefix(table_data, 0, 2);
2554    /* IOMMU info */
2555    build_append_int_noprefix(table_data, 0, 2);
2556    /* IOMMU Feature Reporting */
2557    build_append_int_noprefix(table_data,
2558                             (48UL << 30) | /* HATS   */
2559                             (48UL << 28) | /* GATS   */
2560                             (1UL << 2),    /* GTSup  */
2561                             4);
2562    /*
2563     *   Type 1 device entry reporting all devices
2564     *   These are 4-byte device entries currently reporting the range of
2565     *   Refer to Spec - Table 95:IVHD Device Entry Type Codes(4-byte)
2566     */
2567    build_append_int_noprefix(table_data, 0x0000001, 4);
2568
2569    build_header(linker, table_data, (void *)(table_data->data + iommu_start),
2570                 "IVRS", table_data->len - iommu_start, 1, NULL, NULL);
2571}
2572
2573static GArray *
2574build_rsdp(GArray *rsdp_table, BIOSLinker *linker, unsigned rsdt_tbl_offset)
2575{
2576    AcpiRsdpDescriptor *rsdp = acpi_data_push(rsdp_table, sizeof *rsdp);
2577    unsigned rsdt_pa_size = sizeof(rsdp->rsdt_physical_address);
2578    unsigned rsdt_pa_offset =
2579        (char *)&rsdp->rsdt_physical_address - rsdp_table->data;
2580
2581    bios_linker_loader_alloc(linker, ACPI_BUILD_RSDP_FILE, rsdp_table, 16,
2582                             true /* fseg memory */);
2583
2584    memcpy(&rsdp->signature, "RSD PTR ", 8);
2585    memcpy(rsdp->oem_id, ACPI_BUILD_APPNAME6, 6);
2586    /* Address to be filled by Guest linker */
2587    bios_linker_loader_add_pointer(linker,
2588        ACPI_BUILD_RSDP_FILE, rsdt_pa_offset, rsdt_pa_size,
2589        ACPI_BUILD_TABLE_FILE, rsdt_tbl_offset);
2590
2591    /* Checksum to be filled by Guest linker */
2592    bios_linker_loader_add_checksum(linker, ACPI_BUILD_RSDP_FILE,
2593        (char *)rsdp - rsdp_table->data, sizeof *rsdp,
2594        (char *)&rsdp->checksum - rsdp_table->data);
2595
2596    return rsdp_table;
2597}
2598
2599typedef
2600struct AcpiBuildState {
2601    /* Copy of table in RAM (for patching). */
2602    MemoryRegion *table_mr;
2603    /* Is table patched? */
2604    uint8_t patched;
2605    void *rsdp;
2606    MemoryRegion *rsdp_mr;
2607    MemoryRegion *linker_mr;
2608} AcpiBuildState;
2609
2610static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
2611{
2612    Object *pci_host;
2613    QObject *o;
2614
2615    pci_host = acpi_get_i386_pci_host();
2616    g_assert(pci_host);
2617
2618    o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_BASE, NULL);
2619    if (!o) {
2620        return false;
2621    }
2622    mcfg->mcfg_base = qnum_get_uint(qobject_to_qnum(o));
2623    qobject_decref(o);
2624
2625    o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_SIZE, NULL);
2626    assert(o);
2627    mcfg->mcfg_size = qnum_get_uint(qobject_to_qnum(o));
2628    qobject_decref(o);
2629    return true;
2630}
2631
2632static
2633void acpi_build(AcpiBuildTables *tables, MachineState *machine)
2634{
2635    PCMachineState *pcms = PC_MACHINE(machine);
2636    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
2637    GArray *table_offsets;
2638    unsigned facs, dsdt, rsdt, fadt;
2639    AcpiPmInfo pm;
2640    AcpiMiscInfo misc;
2641    AcpiMcfgInfo mcfg;
2642    Range pci_hole, pci_hole64;
2643    uint8_t *u;
2644    size_t aml_len = 0;
2645    GArray *tables_blob = tables->table_data;
2646    AcpiSlicOem slic_oem = { .id = NULL, .table_id = NULL };
2647    Object *vmgenid_dev;
2648
2649    acpi_get_pm_info(&pm);
2650    acpi_get_misc_info(&misc);
2651    acpi_get_pci_holes(&pci_hole, &pci_hole64);
2652    acpi_get_slic_oem(&slic_oem);
2653
2654    table_offsets = g_array_new(false, true /* clear */,
2655                                        sizeof(uint32_t));
2656    ACPI_BUILD_DPRINTF("init ACPI tables\n");
2657
2658    bios_linker_loader_alloc(tables->linker,
2659                             ACPI_BUILD_TABLE_FILE, tables_blob,
2660                             64 /* Ensure FACS is aligned */,
2661                             false /* high memory */);
2662
2663    /*
2664     * FACS is pointed to by FADT.
2665     * We place it first since it's the only table that has alignment
2666     * requirements.
2667     */
2668    facs = tables_blob->len;
2669    build_facs(tables_blob, tables->linker);
2670
2671    /* DSDT is pointed to by FADT */
2672    dsdt = tables_blob->len;
2673    build_dsdt(tables_blob, tables->linker, &pm, &misc,
2674               &pci_hole, &pci_hole64, machine);
2675
2676    /* Count the size of the DSDT and SSDT, we will need it for legacy
2677     * sizing of ACPI tables.
2678     */
2679    aml_len += tables_blob->len - dsdt;
2680
2681    /* ACPI tables pointed to by RSDT */
2682    fadt = tables_blob->len;
2683    acpi_add_table(table_offsets, tables_blob);
2684    build_fadt(tables_blob, tables->linker, &pm, facs, dsdt,
2685               slic_oem.id, slic_oem.table_id);
2686    aml_len += tables_blob->len - fadt;
2687
2688    acpi_add_table(table_offsets, tables_blob);
2689    build_madt(tables_blob, tables->linker, pcms);
2690
2691    vmgenid_dev = find_vmgenid_dev();
2692    if (vmgenid_dev) {
2693        acpi_add_table(table_offsets, tables_blob);
2694        vmgenid_build_acpi(VMGENID(vmgenid_dev), tables_blob,
2695                           tables->vmgenid, tables->linker);
2696    }
2697
2698    if (misc.has_hpet) {
2699        acpi_add_table(table_offsets, tables_blob);
2700        build_hpet(tables_blob, tables->linker);
2701    }
2702    if (misc.tpm_version != TPM_VERSION_UNSPEC) {
2703        acpi_add_table(table_offsets, tables_blob);
2704        build_tpm_tcpa(tables_blob, tables->linker, tables->tcpalog);
2705
2706        if (misc.tpm_version == TPM_VERSION_2_0) {
2707            acpi_add_table(table_offsets, tables_blob);
2708            build_tpm2(tables_blob, tables->linker);
2709        }
2710    }
2711    if (pcms->numa_nodes) {
2712        acpi_add_table(table_offsets, tables_blob);
2713        build_srat(tables_blob, tables->linker, machine);
2714        if (have_numa_distance) {
2715            acpi_add_table(table_offsets, tables_blob);
2716            build_slit(tables_blob, tables->linker);
2717        }
2718    }
2719    if (acpi_get_mcfg(&mcfg)) {
2720        acpi_add_table(table_offsets, tables_blob);
2721        build_mcfg_q35(tables_blob, tables->linker, &mcfg);
2722    }
2723    if (x86_iommu_get_default()) {
2724        IommuType IOMMUType = x86_iommu_get_type();
2725        if (IOMMUType == TYPE_AMD) {
2726            acpi_add_table(table_offsets, tables_blob);
2727            build_amd_iommu(tables_blob, tables->linker);
2728        } else if (IOMMUType == TYPE_INTEL) {
2729            acpi_add_table(table_offsets, tables_blob);
2730            build_dmar_q35(tables_blob, tables->linker);
2731        }
2732    }
2733    if (pcms->acpi_nvdimm_state.is_enabled) {
2734        nvdimm_build_acpi(table_offsets, tables_blob, tables->linker,
2735                          &pcms->acpi_nvdimm_state, machine->ram_slots);
2736    }
2737
2738    /* Add tables supplied by user (if any) */
2739    for (u = acpi_table_first(); u; u = acpi_table_next(u)) {
2740        unsigned len = acpi_table_len(u);
2741
2742        acpi_add_table(table_offsets, tables_blob);
2743        g_array_append_vals(tables_blob, u, len);
2744    }
2745
2746    /* RSDT is pointed to by RSDP */
2747    rsdt = tables_blob->len;
2748    build_rsdt(tables_blob, tables->linker, table_offsets,
2749               slic_oem.id, slic_oem.table_id);
2750
2751    /* RSDP is in FSEG memory, so allocate it separately */
2752    build_rsdp(tables->rsdp, tables->linker, rsdt);
2753
2754    /* We'll expose it all to Guest so we want to reduce
2755     * chance of size changes.
2756     *
2757     * We used to align the tables to 4k, but of course this would
2758     * too simple to be enough.  4k turned out to be too small an
2759     * alignment very soon, and in fact it is almost impossible to
2760     * keep the table size stable for all (max_cpus, max_memory_slots)
2761     * combinations.  So the table size is always 64k for pc-i440fx-2.1
2762     * and we give an error if the table grows beyond that limit.
2763     *
2764     * We still have the problem of migrating from "-M pc-i440fx-2.0".  For
2765     * that, we exploit the fact that QEMU 2.1 generates _smaller_ tables
2766     * than 2.0 and we can always pad the smaller tables with zeros.  We can
2767     * then use the exact size of the 2.0 tables.
2768     *
2769     * All this is for PIIX4, since QEMU 2.0 didn't support Q35 migration.
2770     */
2771    if (pcmc->legacy_acpi_table_size) {
2772        /* Subtracting aml_len gives the size of fixed tables.  Then add the
2773         * size of the PIIX4 DSDT/SSDT in QEMU 2.0.
2774         */
2775        int legacy_aml_len =
2776            pcmc->legacy_acpi_table_size +
2777            ACPI_BUILD_LEGACY_CPU_AML_SIZE * pcms->apic_id_limit;
2778        int legacy_table_size =
2779            ROUND_UP(tables_blob->len - aml_len + legacy_aml_len,
2780                     ACPI_BUILD_ALIGN_SIZE);
2781        if (tables_blob->len > legacy_table_size) {
2782            /* Should happen only with PCI bridges and -M pc-i440fx-2.0.  */
2783            warn_report("migration may not work.");
2784        }
2785        g_array_set_size(tables_blob, legacy_table_size);
2786    } else {
2787        /* Make sure we have a buffer in case we need to resize the tables. */
2788        if (tables_blob->len > ACPI_BUILD_TABLE_SIZE / 2) {
2789            /* As of QEMU 2.1, this fires with 160 VCPUs and 255 memory slots.  */
2790            warn_report("ACPI tables are larger than 64k.");
2791            warn_report("migration may not work.");
2792            warn_report("please remove CPUs, NUMA nodes, "
2793                        "memory slots or PCI bridges.");
2794        }
2795        acpi_align_size(tables_blob, ACPI_BUILD_TABLE_SIZE);
2796    }
2797
2798    acpi_align_size(tables->linker->cmd_blob, ACPI_BUILD_ALIGN_SIZE);
2799
2800    /* Cleanup memory that's no longer used. */
2801    g_array_free(table_offsets, true);
2802}
2803
2804static void acpi_ram_update(MemoryRegion *mr, GArray *data)
2805{
2806    uint32_t size = acpi_data_len(data);
2807
2808    /* Make sure RAM size is correct - in case it got changed e.g. by migration */
2809    memory_region_ram_resize(mr, size, &error_abort);
2810
2811    memcpy(memory_region_get_ram_ptr(mr), data->data, size);
2812    memory_region_set_dirty(mr, 0, size);
2813}
2814
2815static void acpi_build_update(void *build_opaque)
2816{
2817    AcpiBuildState *build_state = build_opaque;
2818    AcpiBuildTables tables;
2819
2820    /* No state to update or already patched? Nothing to do. */
2821    if (!build_state || build_state->patched) {
2822        return;
2823    }
2824    build_state->patched = 1;
2825
2826    acpi_build_tables_init(&tables);
2827
2828    acpi_build(&tables, MACHINE(qdev_get_machine()));
2829
2830    acpi_ram_update(build_state->table_mr, tables.table_data);
2831
2832    if (build_state->rsdp) {
2833        memcpy(build_state->rsdp, tables.rsdp->data, acpi_data_len(tables.rsdp));
2834    } else {
2835        acpi_ram_update(build_state->rsdp_mr, tables.rsdp);
2836    }
2837
2838    acpi_ram_update(build_state->linker_mr, tables.linker->cmd_blob);
2839    acpi_build_tables_cleanup(&tables, true);
2840}
2841
2842static void acpi_build_reset(void *build_opaque)
2843{
2844    AcpiBuildState *build_state = build_opaque;
2845    build_state->patched = 0;
2846}
2847
2848static MemoryRegion *acpi_add_rom_blob(AcpiBuildState *build_state,
2849                                       GArray *blob, const char *name,
2850                                       uint64_t max_size)
2851{
2852    return rom_add_blob(name, blob->data, acpi_data_len(blob), max_size, -1,
2853                        name, acpi_build_update, build_state, NULL, true);
2854}
2855
2856static const VMStateDescription vmstate_acpi_build = {
2857    .name = "acpi_build",
2858    .version_id = 1,
2859    .minimum_version_id = 1,
2860    .fields = (VMStateField[]) {
2861        VMSTATE_UINT8(patched, AcpiBuildState),
2862        VMSTATE_END_OF_LIST()
2863    },
2864};
2865
2866void acpi_setup(void)
2867{
2868    PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
2869    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
2870    AcpiBuildTables tables;
2871    AcpiBuildState *build_state;
2872    Object *vmgenid_dev;
2873
2874    if (!pcms->fw_cfg) {
2875        ACPI_BUILD_DPRINTF("No fw cfg. Bailing out.\n");
2876        return;
2877    }
2878
2879    if (!pcms->acpi_build_enabled) {
2880        ACPI_BUILD_DPRINTF("ACPI build disabled. Bailing out.\n");
2881        return;
2882    }
2883
2884    if (!acpi_enabled) {
2885        ACPI_BUILD_DPRINTF("ACPI disabled. Bailing out.\n");
2886        return;
2887    }
2888
2889    build_state = g_malloc0(sizeof *build_state);
2890
2891    acpi_set_pci_info();
2892
2893    acpi_build_tables_init(&tables);
2894    acpi_build(&tables, MACHINE(pcms));
2895
2896    /* Now expose it all to Guest */
2897    build_state->table_mr = acpi_add_rom_blob(build_state, tables.table_data,
2898                                               ACPI_BUILD_TABLE_FILE,
2899                                               ACPI_BUILD_TABLE_MAX_SIZE);
2900    assert(build_state->table_mr != NULL);
2901
2902    build_state->linker_mr =
2903        acpi_add_rom_blob(build_state, tables.linker->cmd_blob,
2904                          "etc/table-loader", 0);
2905
2906    fw_cfg_add_file(pcms->fw_cfg, ACPI_BUILD_TPMLOG_FILE,
2907                    tables.tcpalog->data, acpi_data_len(tables.tcpalog));
2908
2909    vmgenid_dev = find_vmgenid_dev();
2910    if (vmgenid_dev) {
2911        vmgenid_add_fw_cfg(VMGENID(vmgenid_dev), pcms->fw_cfg,
2912                           tables.vmgenid);
2913    }
2914
2915    if (!pcmc->rsdp_in_ram) {
2916        /*
2917         * Keep for compatibility with old machine types.
2918         * Though RSDP is small, its contents isn't immutable, so
2919         * we'll update it along with the rest of tables on guest access.
2920         */
2921        uint32_t rsdp_size = acpi_data_len(tables.rsdp);
2922
2923        build_state->rsdp = g_memdup(tables.rsdp->data, rsdp_size);
2924        fw_cfg_add_file_callback(pcms->fw_cfg, ACPI_BUILD_RSDP_FILE,
2925                                 acpi_build_update, build_state,
2926                                 build_state->rsdp, rsdp_size, true);
2927        build_state->rsdp_mr = NULL;
2928    } else {
2929        build_state->rsdp = NULL;
2930        build_state->rsdp_mr = acpi_add_rom_blob(build_state, tables.rsdp,
2931                                                  ACPI_BUILD_RSDP_FILE, 0);
2932    }
2933
2934    qemu_register_reset(acpi_build_reset, build_state);
2935    acpi_build_reset(build_state);
2936    vmstate_register(NULL, 0, &vmstate_acpi_build, build_state);
2937
2938    /* Cleanup tables but don't free the memory: we track it
2939     * in build_state.
2940     */
2941    acpi_build_tables_cleanup(&tables, false);
2942}
2943