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