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 "qapi/qmp/qnum.h"
  26#include "acpi-build.h"
  27#include "acpi-common.h"
  28#include "qemu/bitmap.h"
  29#include "qemu/error-report.h"
  30#include "hw/pci/pci.h"
  31#include "hw/core/cpu.h"
  32#include "target/i386/cpu.h"
  33#include "hw/misc/pvpanic.h"
  34#include "hw/timer/hpet.h"
  35#include "hw/acpi/acpi-defs.h"
  36#include "hw/acpi/acpi.h"
  37#include "hw/acpi/cpu.h"
  38#include "hw/nvram/fw_cfg.h"
  39#include "hw/acpi/bios-linker-loader.h"
  40#include "hw/isa/isa.h"
  41#include "hw/block/fdc.h"
  42#include "hw/acpi/memory_hotplug.h"
  43#include "sysemu/tpm.h"
  44#include "hw/acpi/tpm.h"
  45#include "hw/acpi/vmgenid.h"
  46#include "hw/boards.h"
  47#include "sysemu/tpm_backend.h"
  48#include "hw/rtc/mc146818rtc_regs.h"
  49#include "migration/vmstate.h"
  50#include "hw/mem/memory-device.h"
  51#include "hw/mem/nvdimm.h"
  52#include "sysemu/numa.h"
  53#include "sysemu/reset.h"
  54#include "hw/hyperv/vmbus-bridge.h"
  55
  56/* Supported chipsets: */
  57#include "hw/southbridge/piix.h"
  58#include "hw/acpi/pcihp.h"
  59#include "hw/i386/fw_cfg.h"
  60#include "hw/i386/ich9.h"
  61#include "hw/pci/pci_bus.h"
  62#include "hw/pci-host/q35.h"
  63#include "hw/i386/x86-iommu.h"
  64
  65#include "hw/acpi/aml-build.h"
  66#include "hw/acpi/utils.h"
  67#include "hw/acpi/pci.h"
  68
  69#include "qom/qom-qobject.h"
  70#include "hw/i386/amd_iommu.h"
  71#include "hw/i386/intel_iommu.h"
  72
  73#include "hw/acpi/ipmi.h"
  74#include "hw/acpi/hmat.h"
  75
  76/* These are used to size the ACPI tables for -M pc-i440fx-1.7 and
  77 * -M pc-i440fx-2.0.  Even if the actual amount of AML generated grows
  78 * a little bit, there should be plenty of free space since the DSDT
  79 * shrunk by ~1.5k between QEMU 2.0 and QEMU 2.1.
  80 */
  81#define ACPI_BUILD_LEGACY_CPU_AML_SIZE    97
  82#define ACPI_BUILD_ALIGN_SIZE             0x1000
  83
  84#define ACPI_BUILD_TABLE_SIZE             0x20000
  85
  86/* #define DEBUG_ACPI_BUILD */
  87#ifdef DEBUG_ACPI_BUILD
  88#define ACPI_BUILD_DPRINTF(fmt, ...)        \
  89    do {printf("ACPI_BUILD: " fmt, ## __VA_ARGS__); } while (0)
  90#else
  91#define ACPI_BUILD_DPRINTF(fmt, ...)
  92#endif
  93
  94typedef struct AcpiPmInfo {
  95    bool s3_disabled;
  96    bool s4_disabled;
  97    bool pcihp_bridge_en;
  98    bool smi_on_cpuhp;
  99    bool smi_on_cpu_unplug;
 100    bool pcihp_root_en;
 101    uint8_t s4_val;
 102    AcpiFadtData fadt;
 103    uint16_t cpu_hp_io_base;
 104    uint16_t pcihp_io_base;
 105    uint16_t pcihp_io_len;
 106} AcpiPmInfo;
 107
 108typedef struct AcpiMiscInfo {
 109    bool is_piix4;
 110    bool has_hpet;
 111    TPMVersion tpm_version;
 112    const unsigned char *dsdt_code;
 113    unsigned dsdt_size;
 114    uint16_t pvpanic_port;
 115    uint16_t applesmc_io_base;
 116} AcpiMiscInfo;
 117
 118typedef struct AcpiBuildPciBusHotplugState {
 119    GArray *device_table;
 120    GArray *notify_table;
 121    struct AcpiBuildPciBusHotplugState *parent;
 122    bool pcihp_bridge_en;
 123} AcpiBuildPciBusHotplugState;
 124
 125typedef struct FwCfgTPMConfig {
 126    uint32_t tpmppi_address;
 127    uint8_t tpm_version;
 128    uint8_t tpmppi_version;
 129} QEMU_PACKED FwCfgTPMConfig;
 130
 131static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg);
 132
 133const struct AcpiGenericAddress x86_nvdimm_acpi_dsmio = {
 134    .space_id = AML_AS_SYSTEM_IO,
 135    .address = NVDIMM_ACPI_IO_BASE,
 136    .bit_width = NVDIMM_ACPI_IO_LEN << 3
 137};
 138
 139static void init_common_fadt_data(MachineState *ms, Object *o,
 140                                  AcpiFadtData *data)
 141{
 142    X86MachineState *x86ms = X86_MACHINE(ms);
 143    /*
 144     * "ICH9-LPC" or "PIIX4_PM" has "smm-compat" property to keep the old
 145     * behavior for compatibility irrelevant to smm_enabled, which doesn't
 146     * comforms to ACPI spec.
 147     */
 148    bool smm_enabled = object_property_get_bool(o, "smm-compat", NULL) ?
 149        true : x86_machine_is_smm_enabled(x86ms);
 150    uint32_t io = object_property_get_uint(o, ACPI_PM_PROP_PM_IO_BASE, NULL);
 151    AmlAddressSpace as = AML_AS_SYSTEM_IO;
 152    AcpiFadtData fadt = {
 153        .rev = 3,
 154        .flags =
 155            (1 << ACPI_FADT_F_WBINVD) |
 156            (1 << ACPI_FADT_F_PROC_C1) |
 157            (1 << ACPI_FADT_F_SLP_BUTTON) |
 158            (1 << ACPI_FADT_F_RTC_S4) |
 159            (1 << ACPI_FADT_F_USE_PLATFORM_CLOCK) |
 160            /* APIC destination mode ("Flat Logical") has an upper limit of 8
 161             * CPUs for more than 8 CPUs, "Clustered Logical" mode has to be
 162             * used
 163             */
 164            ((ms->smp.max_cpus > 8) ?
 165                        (1 << ACPI_FADT_F_FORCE_APIC_CLUSTER_MODEL) : 0),
 166        .int_model = 1 /* Multiple APIC */,
 167        .rtc_century = RTC_CENTURY,
 168        .plvl2_lat = 0xfff /* C2 state not supported */,
 169        .plvl3_lat = 0xfff /* C3 state not supported */,
 170        .smi_cmd = smm_enabled ? ACPI_PORT_SMI_CMD : 0,
 171        .sci_int = object_property_get_uint(o, ACPI_PM_PROP_SCI_INT, NULL),
 172        .acpi_enable_cmd =
 173            smm_enabled ?
 174            object_property_get_uint(o, ACPI_PM_PROP_ACPI_ENABLE_CMD, NULL) :
 175            0,
 176        .acpi_disable_cmd =
 177            smm_enabled ?
 178            object_property_get_uint(o, ACPI_PM_PROP_ACPI_DISABLE_CMD, NULL) :
 179            0,
 180        .pm1a_evt = { .space_id = as, .bit_width = 4 * 8, .address = io },
 181        .pm1a_cnt = { .space_id = as, .bit_width = 2 * 8,
 182                      .address = io + 0x04 },
 183        .pm_tmr = { .space_id = as, .bit_width = 4 * 8, .address = io + 0x08 },
 184        .gpe0_blk = { .space_id = as, .bit_width =
 185            object_property_get_uint(o, ACPI_PM_PROP_GPE0_BLK_LEN, NULL) * 8,
 186            .address = object_property_get_uint(o, ACPI_PM_PROP_GPE0_BLK, NULL)
 187        },
 188    };
 189    *data = fadt;
 190}
 191
 192static Object *object_resolve_type_unambiguous(const char *typename)
 193{
 194    bool ambig;
 195    Object *o = object_resolve_path_type("", typename, &ambig);
 196
 197    if (ambig || !o) {
 198        return NULL;
 199    }
 200    return o;
 201}
 202
 203static void acpi_get_pm_info(MachineState *machine, AcpiPmInfo *pm)
 204{
 205    Object *piix = object_resolve_type_unambiguous(TYPE_PIIX4_PM);
 206    Object *lpc = object_resolve_type_unambiguous(TYPE_ICH9_LPC_DEVICE);
 207    Object *obj = piix ? piix : lpc;
 208    QObject *o;
 209    pm->cpu_hp_io_base = 0;
 210    pm->pcihp_io_base = 0;
 211    pm->pcihp_io_len = 0;
 212    pm->smi_on_cpuhp = false;
 213    pm->smi_on_cpu_unplug = false;
 214
 215    assert(obj);
 216    init_common_fadt_data(machine, obj, &pm->fadt);
 217    if (piix) {
 218        /* w2k requires FADT(rev1) or it won't boot, keep PC compatible */
 219        pm->fadt.rev = 1;
 220        pm->cpu_hp_io_base = PIIX4_CPU_HOTPLUG_IO_BASE;
 221        pm->pcihp_io_base =
 222            object_property_get_uint(obj, ACPI_PCIHP_IO_BASE_PROP, NULL);
 223        pm->pcihp_io_len =
 224            object_property_get_uint(obj, ACPI_PCIHP_IO_LEN_PROP, NULL);
 225    }
 226    if (lpc) {
 227        uint64_t smi_features = object_property_get_uint(lpc,
 228            ICH9_LPC_SMI_NEGOTIATED_FEAT_PROP, NULL);
 229        struct AcpiGenericAddress r = { .space_id = AML_AS_SYSTEM_IO,
 230            .bit_width = 8, .address = ICH9_RST_CNT_IOPORT };
 231        pm->fadt.reset_reg = r;
 232        pm->fadt.reset_val = 0xf;
 233        pm->fadt.flags |= 1 << ACPI_FADT_F_RESET_REG_SUP;
 234        pm->cpu_hp_io_base = ICH9_CPU_HOTPLUG_IO_BASE;
 235        pm->smi_on_cpuhp =
 236            !!(smi_features & BIT_ULL(ICH9_LPC_SMI_F_CPU_HOTPLUG_BIT));
 237        pm->smi_on_cpu_unplug =
 238            !!(smi_features & BIT_ULL(ICH9_LPC_SMI_F_CPU_HOT_UNPLUG_BIT));
 239    }
 240
 241    /* The above need not be conditional on machine type because the reset port
 242     * happens to be the same on PIIX (pc) and ICH9 (q35). */
 243    QEMU_BUILD_BUG_ON(ICH9_RST_CNT_IOPORT != PIIX_RCR_IOPORT);
 244
 245    /* Fill in optional s3/s4 related properties */
 246    o = object_property_get_qobject(obj, ACPI_PM_PROP_S3_DISABLED, NULL);
 247    if (o) {
 248        pm->s3_disabled = qnum_get_uint(qobject_to(QNum, o));
 249    } else {
 250        pm->s3_disabled = false;
 251    }
 252    qobject_unref(o);
 253    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL);
 254    if (o) {
 255        pm->s4_disabled = qnum_get_uint(qobject_to(QNum, o));
 256    } else {
 257        pm->s4_disabled = false;
 258    }
 259    qobject_unref(o);
 260    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL);
 261    if (o) {
 262        pm->s4_val = qnum_get_uint(qobject_to(QNum, o));
 263    } else {
 264        pm->s4_val = false;
 265    }
 266    qobject_unref(o);
 267
 268    pm->pcihp_bridge_en =
 269        object_property_get_bool(obj, "acpi-pci-hotplug-with-bridge-support",
 270                                 NULL);
 271    pm->pcihp_root_en =
 272        object_property_get_bool(obj, "acpi-root-pci-hotplug",
 273                                 NULL);
 274}
 275
 276static void acpi_get_misc_info(AcpiMiscInfo *info)
 277{
 278    Object *piix = object_resolve_type_unambiguous(TYPE_PIIX4_PM);
 279    Object *lpc = object_resolve_type_unambiguous(TYPE_ICH9_LPC_DEVICE);
 280    assert(!!piix != !!lpc);
 281
 282    if (piix) {
 283        info->is_piix4 = true;
 284    }
 285    if (lpc) {
 286        info->is_piix4 = false;
 287    }
 288
 289    info->has_hpet = hpet_find();
 290    info->tpm_version = tpm_get_version(tpm_find());
 291    info->pvpanic_port = pvpanic_port();
 292    info->applesmc_io_base = applesmc_port();
 293}
 294
 295/*
 296 * Because of the PXB hosts we cannot simply query TYPE_PCI_HOST_BRIDGE.
 297 * On i386 arch we only have two pci hosts, so we can look only for them.
 298 */
 299static Object *acpi_get_i386_pci_host(void)
 300{
 301    PCIHostState *host;
 302
 303    host = OBJECT_CHECK(PCIHostState,
 304                        object_resolve_path("/machine/i440fx", NULL),
 305                        TYPE_PCI_HOST_BRIDGE);
 306    if (!host) {
 307        host = OBJECT_CHECK(PCIHostState,
 308                            object_resolve_path("/machine/q35", NULL),
 309                            TYPE_PCI_HOST_BRIDGE);
 310    }
 311
 312    return OBJECT(host);
 313}
 314
 315static void acpi_get_pci_holes(Range *hole, Range *hole64)
 316{
 317    Object *pci_host;
 318
 319    pci_host = acpi_get_i386_pci_host();
 320    g_assert(pci_host);
 321
 322    range_set_bounds1(hole,
 323                      object_property_get_uint(pci_host,
 324                                               PCI_HOST_PROP_PCI_HOLE_START,
 325                                               NULL),
 326                      object_property_get_uint(pci_host,
 327                                               PCI_HOST_PROP_PCI_HOLE_END,
 328                                               NULL));
 329    range_set_bounds1(hole64,
 330                      object_property_get_uint(pci_host,
 331                                               PCI_HOST_PROP_PCI_HOLE64_START,
 332                                               NULL),
 333                      object_property_get_uint(pci_host,
 334                                               PCI_HOST_PROP_PCI_HOLE64_END,
 335                                               NULL));
 336}
 337
 338static void acpi_align_size(GArray *blob, unsigned align)
 339{
 340    /* Align size to multiple of given size. This reduces the chance
 341     * we need to change size in the future (breaking cross version migration).
 342     */
 343    g_array_set_size(blob, ROUND_UP(acpi_data_len(blob), align));
 344}
 345
 346/* FACS */
 347static void
 348build_facs(GArray *table_data)
 349{
 350    AcpiFacsDescriptorRev1 *facs = acpi_data_push(table_data, sizeof *facs);
 351    memcpy(&facs->signature, "FACS", 4);
 352    facs->length = cpu_to_le32(sizeof(*facs));
 353}
 354
 355static void build_append_pcihp_notify_entry(Aml *method, int slot)
 356{
 357    Aml *if_ctx;
 358    int32_t devfn = PCI_DEVFN(slot, 0);
 359
 360    if_ctx = aml_if(aml_and(aml_arg(0), aml_int(0x1U << slot), NULL));
 361    aml_append(if_ctx, aml_notify(aml_name("S%.02X", devfn), aml_arg(1)));
 362    aml_append(method, if_ctx);
 363}
 364
 365static void build_append_pci_bus_devices(Aml *parent_scope, PCIBus *bus,
 366                                         bool pcihp_bridge_en)
 367{
 368    Aml *dev, *notify_method = NULL, *method;
 369    QObject *bsel;
 370    PCIBus *sec;
 371    int i;
 372
 373    bsel = object_property_get_qobject(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, NULL);
 374    if (bsel) {
 375        uint64_t bsel_val = qnum_get_uint(qobject_to(QNum, bsel));
 376
 377        aml_append(parent_scope, aml_name_decl("BSEL", aml_int(bsel_val)));
 378        notify_method = aml_method("DVNT", 2, AML_NOTSERIALIZED);
 379    }
 380
 381    for (i = 0; i < ARRAY_SIZE(bus->devices); i += PCI_FUNC_MAX) {
 382        DeviceClass *dc;
 383        PCIDeviceClass *pc;
 384        PCIDevice *pdev = bus->devices[i];
 385        int slot = PCI_SLOT(i);
 386        bool hotplug_enabled_dev;
 387        bool bridge_in_acpi;
 388        bool cold_plugged_bridge;
 389
 390        if (!pdev) {
 391            if (bsel) { /* add hotplug slots for non present devices */
 392                dev = aml_device("S%.02X", PCI_DEVFN(slot, 0));
 393                aml_append(dev, aml_name_decl("_SUN", aml_int(slot)));
 394                aml_append(dev, aml_name_decl("_ADR", aml_int(slot << 16)));
 395                method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);
 396                aml_append(method,
 397                    aml_call2("PCEJ", aml_name("BSEL"), aml_name("_SUN"))
 398                );
 399                aml_append(dev, method);
 400                method = aml_method("_DSM", 4, AML_SERIALIZED);
 401                aml_append(method,
 402                    aml_return(aml_call6("PDSM", aml_arg(0), aml_arg(1),
 403                                         aml_arg(2), aml_arg(3),
 404                                         aml_name("BSEL"), aml_name("_SUN")))
 405                );
 406                aml_append(dev, method);
 407                aml_append(parent_scope, dev);
 408
 409                build_append_pcihp_notify_entry(notify_method, slot);
 410            }
 411            continue;
 412        }
 413
 414        pc = PCI_DEVICE_GET_CLASS(pdev);
 415        dc = DEVICE_GET_CLASS(pdev);
 416
 417        /*
 418         * Cold plugged bridges aren't themselves hot-pluggable.
 419         * Hotplugged bridges *are* hot-pluggable.
 420         */
 421        cold_plugged_bridge = pc->is_bridge && !DEVICE(pdev)->hotplugged;
 422        bridge_in_acpi =  cold_plugged_bridge && pcihp_bridge_en;
 423
 424        hotplug_enabled_dev = bsel && dc->hotpluggable && !cold_plugged_bridge;
 425
 426        if (pc->class_id == PCI_CLASS_BRIDGE_ISA) {
 427            continue;
 428        }
 429
 430        /* start to compose PCI slot descriptor */
 431        dev = aml_device("S%.02X", PCI_DEVFN(slot, 0));
 432        aml_append(dev, aml_name_decl("_ADR", aml_int(slot << 16)));
 433
 434        if (bsel) {
 435            /*
 436             * Can't declare _SUN here for every device as it changes 'slot'
 437             * enumeration order in linux kernel, so use another variable for it
 438             */
 439            aml_append(dev, aml_name_decl("ASUN", aml_int(slot)));
 440            method = aml_method("_DSM", 4, AML_SERIALIZED);
 441            aml_append(method, aml_return(
 442                aml_call6("PDSM", aml_arg(0), aml_arg(1), aml_arg(2),
 443                          aml_arg(3), aml_name("BSEL"), aml_name("ASUN"))
 444            ));
 445            aml_append(dev, method);
 446        }
 447
 448        if (pc->class_id == PCI_CLASS_DISPLAY_VGA) {
 449            /* add VGA specific AML methods */
 450            int s3d;
 451
 452            if (object_dynamic_cast(OBJECT(pdev), "qxl-vga")) {
 453                s3d = 3;
 454            } else {
 455                s3d = 0;
 456            }
 457
 458            method = aml_method("_S1D", 0, AML_NOTSERIALIZED);
 459            aml_append(method, aml_return(aml_int(0)));
 460            aml_append(dev, method);
 461
 462            method = aml_method("_S2D", 0, AML_NOTSERIALIZED);
 463            aml_append(method, aml_return(aml_int(0)));
 464            aml_append(dev, method);
 465
 466            method = aml_method("_S3D", 0, AML_NOTSERIALIZED);
 467            aml_append(method, aml_return(aml_int(s3d)));
 468            aml_append(dev, method);
 469        } else if (hotplug_enabled_dev) {
 470            aml_append(dev, aml_name_decl("_SUN", aml_int(slot)));
 471            /* add _EJ0 to make slot hotpluggable  */
 472            method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);
 473            aml_append(method,
 474                aml_call2("PCEJ", aml_name("BSEL"), aml_name("_SUN"))
 475            );
 476            aml_append(dev, method);
 477
 478            if (bsel) {
 479                build_append_pcihp_notify_entry(notify_method, slot);
 480            }
 481        } else if (bridge_in_acpi) {
 482            /*
 483             * device is coldplugged bridge,
 484             * add child device descriptions into its scope
 485             */
 486            PCIBus *sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
 487
 488            build_append_pci_bus_devices(dev, sec_bus, pcihp_bridge_en);
 489        }
 490        /* slot descriptor has been composed, add it into parent context */
 491        aml_append(parent_scope, dev);
 492    }
 493
 494    if (bsel) {
 495        aml_append(parent_scope, notify_method);
 496    }
 497
 498    /* Append PCNT method to notify about events on local and child buses.
 499     * Add this method for root bus only when hotplug is enabled since DSDT
 500     * expects it.
 501     */
 502    if (bsel || pcihp_bridge_en) {
 503        method = aml_method("PCNT", 0, AML_NOTSERIALIZED);
 504
 505        /* If bus supports hotplug select it and notify about local events */
 506        if (bsel) {
 507            uint64_t bsel_val = qnum_get_uint(qobject_to(QNum, bsel));
 508
 509            aml_append(method, aml_store(aml_int(bsel_val), aml_name("BNUM")));
 510            aml_append(method, aml_call2("DVNT", aml_name("PCIU"),
 511                                         aml_int(1))); /* Device Check */
 512            aml_append(method, aml_call2("DVNT", aml_name("PCID"),
 513                                         aml_int(3))); /* Eject Request */
 514        }
 515
 516        /* Notify about child bus events in any case */
 517        if (pcihp_bridge_en) {
 518            QLIST_FOREACH(sec, &bus->child, sibling) {
 519                int32_t devfn = sec->parent_dev->devfn;
 520
 521                if (pci_bus_is_root(sec) || pci_bus_is_express(sec)) {
 522                    continue;
 523                }
 524
 525                aml_append(method, aml_name("^S%.02X.PCNT", devfn));
 526            }
 527        }
 528
 529        aml_append(parent_scope, method);
 530    }
 531    qobject_unref(bsel);
 532}
 533
 534Aml *aml_pci_device_dsm(void)
 535{
 536    Aml *method, *UUID, *ifctx, *ifctx1, *ifctx2, *ifctx3, *elsectx;
 537    Aml *acpi_index = aml_local(0);
 538    Aml *zero = aml_int(0);
 539    Aml *bnum = aml_arg(4);
 540    Aml *func = aml_arg(2);
 541    Aml *rev = aml_arg(1);
 542    Aml *sun = aml_arg(5);
 543
 544    method = aml_method("PDSM", 6, AML_SERIALIZED);
 545
 546    /*
 547     * PCI Firmware Specification 3.1
 548     * 4.6.  _DSM Definitions for PCI
 549     */
 550    UUID = aml_touuid("E5C937D0-3553-4D7A-9117-EA4D19C3434D");
 551    ifctx = aml_if(aml_equal(aml_arg(0), UUID));
 552    {
 553        aml_append(ifctx, aml_store(aml_call2("AIDX", bnum, sun), acpi_index));
 554        ifctx1 = aml_if(aml_equal(func, zero));
 555        {
 556            uint8_t byte_list[1];
 557
 558            ifctx2 = aml_if(aml_equal(rev, aml_int(2)));
 559            {
 560                /*
 561                 * advertise function 7 if device has acpi-index
 562                 * acpi_index values:
 563                 *            0: not present (default value)
 564                 *     FFFFFFFF: not supported (old QEMU without PIDX reg)
 565                 *        other: device's acpi-index
 566                 */
 567                ifctx3 = aml_if(aml_lnot(
 568                    aml_or(aml_equal(acpi_index, zero),
 569                           aml_equal(acpi_index, aml_int(0xFFFFFFFF)), NULL)
 570                ));
 571                {
 572                    byte_list[0] =
 573                        1 /* have supported functions */ |
 574                        1 << 7 /* support for function 7 */
 575                    ;
 576                    aml_append(ifctx3, aml_return(aml_buffer(1, byte_list)));
 577                }
 578                aml_append(ifctx2, ifctx3);
 579             }
 580             aml_append(ifctx1, ifctx2);
 581
 582             byte_list[0] = 0; /* nothing supported */
 583             aml_append(ifctx1, aml_return(aml_buffer(1, byte_list)));
 584         }
 585         aml_append(ifctx, ifctx1);
 586         elsectx = aml_else();
 587         /*
 588          * PCI Firmware Specification 3.1
 589          * 4.6.7. _DSM for Naming a PCI or PCI Express Device Under
 590          *        Operating Systems
 591          */
 592         ifctx1 = aml_if(aml_equal(func, aml_int(7)));
 593         {
 594             Aml *pkg = aml_package(2);
 595             Aml *ret = aml_local(1);
 596
 597             aml_append(pkg, zero);
 598             /*
 599              * optional, if not impl. should return null string
 600              */
 601             aml_append(pkg, aml_string("%s", ""));
 602             aml_append(ifctx1, aml_store(pkg, ret));
 603             /*
 604              * update acpi-index to actual value
 605              */
 606             aml_append(ifctx1, aml_store(acpi_index, aml_index(ret, zero)));
 607             aml_append(ifctx1, aml_return(ret));
 608         }
 609         aml_append(elsectx, ifctx1);
 610         aml_append(ifctx, elsectx);
 611    }
 612    aml_append(method, ifctx);
 613    return method;
 614}
 615
 616/**
 617 * build_prt_entry:
 618 * @link_name: link name for PCI route entry
 619 *
 620 * build AML package containing a PCI route entry for @link_name
 621 */
 622static Aml *build_prt_entry(const char *link_name)
 623{
 624    Aml *a_zero = aml_int(0);
 625    Aml *pkg = aml_package(4);
 626    aml_append(pkg, a_zero);
 627    aml_append(pkg, a_zero);
 628    aml_append(pkg, aml_name("%s", link_name));
 629    aml_append(pkg, a_zero);
 630    return pkg;
 631}
 632
 633/*
 634 * initialize_route - Initialize the interrupt routing rule
 635 * through a specific LINK:
 636 *  if (lnk_idx == idx)
 637 *      route using link 'link_name'
 638 */
 639static Aml *initialize_route(Aml *route, const char *link_name,
 640                             Aml *lnk_idx, int idx)
 641{
 642    Aml *if_ctx = aml_if(aml_equal(lnk_idx, aml_int(idx)));
 643    Aml *pkg = build_prt_entry(link_name);
 644
 645    aml_append(if_ctx, aml_store(pkg, route));
 646
 647    return if_ctx;
 648}
 649
 650/*
 651 * build_prt - Define interrupt rounting rules
 652 *
 653 * Returns an array of 128 routes, one for each device,
 654 * based on device location.
 655 * The main goal is to equaly distribute the interrupts
 656 * over the 4 existing ACPI links (works only for i440fx).
 657 * The hash function is  (slot + pin) & 3 -> "LNK[D|A|B|C]".
 658 *
 659 */
 660static Aml *build_prt(bool is_pci0_prt)
 661{
 662    Aml *method, *while_ctx, *pin, *res;
 663
 664    method = aml_method("_PRT", 0, AML_NOTSERIALIZED);
 665    res = aml_local(0);
 666    pin = aml_local(1);
 667    aml_append(method, aml_store(aml_package(128), res));
 668    aml_append(method, aml_store(aml_int(0), pin));
 669
 670    /* while (pin < 128) */
 671    while_ctx = aml_while(aml_lless(pin, aml_int(128)));
 672    {
 673        Aml *slot = aml_local(2);
 674        Aml *lnk_idx = aml_local(3);
 675        Aml *route = aml_local(4);
 676
 677        /* slot = pin >> 2 */
 678        aml_append(while_ctx,
 679                   aml_store(aml_shiftright(pin, aml_int(2), NULL), slot));
 680        /* lnk_idx = (slot + pin) & 3 */
 681        aml_append(while_ctx,
 682            aml_store(aml_and(aml_add(pin, slot, NULL), aml_int(3), NULL),
 683                      lnk_idx));
 684
 685        /* route[2] = "LNK[D|A|B|C]", selection based on pin % 3  */
 686        aml_append(while_ctx, initialize_route(route, "LNKD", lnk_idx, 0));
 687        if (is_pci0_prt) {
 688            Aml *if_device_1, *if_pin_4, *else_pin_4;
 689
 690            /* device 1 is the power-management device, needs SCI */
 691            if_device_1 = aml_if(aml_equal(lnk_idx, aml_int(1)));
 692            {
 693                if_pin_4 = aml_if(aml_equal(pin, aml_int(4)));
 694                {
 695                    aml_append(if_pin_4,
 696                        aml_store(build_prt_entry("LNKS"), route));
 697                }
 698                aml_append(if_device_1, if_pin_4);
 699                else_pin_4 = aml_else();
 700                {
 701                    aml_append(else_pin_4,
 702                        aml_store(build_prt_entry("LNKA"), route));
 703                }
 704                aml_append(if_device_1, else_pin_4);
 705            }
 706            aml_append(while_ctx, if_device_1);
 707        } else {
 708            aml_append(while_ctx, initialize_route(route, "LNKA", lnk_idx, 1));
 709        }
 710        aml_append(while_ctx, initialize_route(route, "LNKB", lnk_idx, 2));
 711        aml_append(while_ctx, initialize_route(route, "LNKC", lnk_idx, 3));
 712
 713        /* route[0] = 0x[slot]FFFF */
 714        aml_append(while_ctx,
 715            aml_store(aml_or(aml_shiftleft(slot, aml_int(16)), aml_int(0xFFFF),
 716                             NULL),
 717                      aml_index(route, aml_int(0))));
 718        /* route[1] = pin & 3 */
 719        aml_append(while_ctx,
 720            aml_store(aml_and(pin, aml_int(3), NULL),
 721                      aml_index(route, aml_int(1))));
 722        /* res[pin] = route */
 723        aml_append(while_ctx, aml_store(route, aml_index(res, pin)));
 724        /* pin++ */
 725        aml_append(while_ctx, aml_increment(pin));
 726    }
 727    aml_append(method, while_ctx);
 728    /* return res*/
 729    aml_append(method, aml_return(res));
 730
 731    return method;
 732}
 733
 734static void build_hpet_aml(Aml *table)
 735{
 736    Aml *crs;
 737    Aml *field;
 738    Aml *method;
 739    Aml *if_ctx;
 740    Aml *scope = aml_scope("_SB");
 741    Aml *dev = aml_device("HPET");
 742    Aml *zero = aml_int(0);
 743    Aml *id = aml_local(0);
 744    Aml *period = aml_local(1);
 745
 746    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0103")));
 747    aml_append(dev, aml_name_decl("_UID", zero));
 748
 749    aml_append(dev,
 750        aml_operation_region("HPTM", AML_SYSTEM_MEMORY, aml_int(HPET_BASE),
 751                             HPET_LEN));
 752    field = aml_field("HPTM", AML_DWORD_ACC, AML_LOCK, AML_PRESERVE);
 753    aml_append(field, aml_named_field("VEND", 32));
 754    aml_append(field, aml_named_field("PRD", 32));
 755    aml_append(dev, field);
 756
 757    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
 758    aml_append(method, aml_store(aml_name("VEND"), id));
 759    aml_append(method, aml_store(aml_name("PRD"), period));
 760    aml_append(method, aml_shiftright(id, aml_int(16), id));
 761    if_ctx = aml_if(aml_lor(aml_equal(id, zero),
 762                            aml_equal(id, aml_int(0xffff))));
 763    {
 764        aml_append(if_ctx, aml_return(zero));
 765    }
 766    aml_append(method, if_ctx);
 767
 768    if_ctx = aml_if(aml_lor(aml_equal(period, zero),
 769                            aml_lgreater(period, aml_int(100000000))));
 770    {
 771        aml_append(if_ctx, aml_return(zero));
 772    }
 773    aml_append(method, if_ctx);
 774
 775    aml_append(method, aml_return(aml_int(0x0F)));
 776    aml_append(dev, method);
 777
 778    crs = aml_resource_template();
 779    aml_append(crs, aml_memory32_fixed(HPET_BASE, HPET_LEN, AML_READ_ONLY));
 780    aml_append(dev, aml_name_decl("_CRS", crs));
 781
 782    aml_append(scope, dev);
 783    aml_append(table, scope);
 784}
 785
 786static Aml *build_vmbus_device_aml(VMBusBridge *vmbus_bridge)
 787{
 788    Aml *dev;
 789    Aml *method;
 790    Aml *crs;
 791
 792    dev = aml_device("VMBS");
 793    aml_append(dev, aml_name_decl("STA", aml_int(0xF)));
 794    aml_append(dev, aml_name_decl("_HID", aml_string("VMBus")));
 795    aml_append(dev, aml_name_decl("_UID", aml_int(0x0)));
 796    aml_append(dev, aml_name_decl("_DDN", aml_string("VMBUS")));
 797
 798    method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
 799    aml_append(method, aml_store(aml_and(aml_name("STA"), aml_int(0xD), NULL),
 800                                     aml_name("STA")));
 801    aml_append(dev, method);
 802
 803    method = aml_method("_PS0", 0, AML_NOTSERIALIZED);
 804    aml_append(method, aml_store(aml_or(aml_name("STA"), aml_int(0xF), NULL),
 805                                     aml_name("STA")));
 806    aml_append(dev, method);
 807
 808    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
 809    aml_append(method, aml_return(aml_name("STA")));
 810    aml_append(dev, method);
 811
 812    aml_append(dev, aml_name_decl("_PS3", aml_int(0x0)));
 813
 814    crs = aml_resource_template();
 815    aml_append(crs, aml_irq_no_flags(vmbus_bridge->irq));
 816    aml_append(dev, aml_name_decl("_CRS", crs));
 817
 818    return dev;
 819}
 820
 821static void build_isa_devices_aml(Aml *table)
 822{
 823    bool ambiguous;
 824    Object *obj = object_resolve_path_type("", TYPE_ISA_BUS, &ambiguous);
 825    Aml *scope;
 826
 827    assert(obj && !ambiguous);
 828
 829    scope = aml_scope("_SB.PCI0.ISA");
 830    build_acpi_ipmi_devices(scope, BUS(obj), "\\_SB.PCI0.ISA");
 831    isa_build_aml(ISA_BUS(obj), scope);
 832
 833    aml_append(table, scope);
 834}
 835
 836static void build_dbg_aml(Aml *table)
 837{
 838    Aml *field;
 839    Aml *method;
 840    Aml *while_ctx;
 841    Aml *scope = aml_scope("\\");
 842    Aml *buf = aml_local(0);
 843    Aml *len = aml_local(1);
 844    Aml *idx = aml_local(2);
 845
 846    aml_append(scope,
 847       aml_operation_region("DBG", AML_SYSTEM_IO, aml_int(0x0402), 0x01));
 848    field = aml_field("DBG", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
 849    aml_append(field, aml_named_field("DBGB", 8));
 850    aml_append(scope, field);
 851
 852    method = aml_method("DBUG", 1, AML_NOTSERIALIZED);
 853
 854    aml_append(method, aml_to_hexstring(aml_arg(0), buf));
 855    aml_append(method, aml_to_buffer(buf, buf));
 856    aml_append(method, aml_subtract(aml_sizeof(buf), aml_int(1), len));
 857    aml_append(method, aml_store(aml_int(0), idx));
 858
 859    while_ctx = aml_while(aml_lless(idx, len));
 860    aml_append(while_ctx,
 861        aml_store(aml_derefof(aml_index(buf, idx)), aml_name("DBGB")));
 862    aml_append(while_ctx, aml_increment(idx));
 863    aml_append(method, while_ctx);
 864
 865    aml_append(method, aml_store(aml_int(0x0A), aml_name("DBGB")));
 866    aml_append(scope, method);
 867
 868    aml_append(table, scope);
 869}
 870
 871static Aml *build_link_dev(const char *name, uint8_t uid, Aml *reg)
 872{
 873    Aml *dev;
 874    Aml *crs;
 875    Aml *method;
 876    uint32_t irqs[] = {5, 10, 11};
 877
 878    dev = aml_device("%s", name);
 879    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C0F")));
 880    aml_append(dev, aml_name_decl("_UID", aml_int(uid)));
 881
 882    crs = aml_resource_template();
 883    aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,
 884                                  AML_SHARED, irqs, ARRAY_SIZE(irqs)));
 885    aml_append(dev, aml_name_decl("_PRS", crs));
 886
 887    method = aml_method("_STA", 0, AML_NOTSERIALIZED);
 888    aml_append(method, aml_return(aml_call1("IQST", reg)));
 889    aml_append(dev, method);
 890
 891    method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
 892    aml_append(method, aml_or(reg, aml_int(0x80), reg));
 893    aml_append(dev, method);
 894
 895    method = aml_method("_CRS", 0, AML_NOTSERIALIZED);
 896    aml_append(method, aml_return(aml_call1("IQCR", reg)));
 897    aml_append(dev, method);
 898
 899    method = aml_method("_SRS", 1, AML_NOTSERIALIZED);
 900    aml_append(method, aml_create_dword_field(aml_arg(0), aml_int(5), "PRRI"));
 901    aml_append(method, aml_store(aml_name("PRRI"), reg));
 902    aml_append(dev, method);
 903
 904    return dev;
 905 }
 906
 907static Aml *build_gsi_link_dev(const char *name, uint8_t uid, uint8_t gsi)
 908{
 909    Aml *dev;
 910    Aml *crs;
 911    Aml *method;
 912    uint32_t irqs;
 913
 914    dev = aml_device("%s", name);
 915    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C0F")));
 916    aml_append(dev, aml_name_decl("_UID", aml_int(uid)));
 917
 918    crs = aml_resource_template();
 919    irqs = gsi;
 920    aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,
 921                                  AML_SHARED, &irqs, 1));
 922    aml_append(dev, aml_name_decl("_PRS", crs));
 923
 924    aml_append(dev, aml_name_decl("_CRS", crs));
 925
 926    /*
 927     * _DIS can be no-op because the interrupt cannot be disabled.
 928     */
 929    method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
 930    aml_append(dev, method);
 931
 932    method = aml_method("_SRS", 1, AML_NOTSERIALIZED);
 933    aml_append(dev, method);
 934
 935    return dev;
 936}
 937
 938/* _CRS method - get current settings */
 939static Aml *build_iqcr_method(bool is_piix4)
 940{
 941    Aml *if_ctx;
 942    uint32_t irqs;
 943    Aml *method = aml_method("IQCR", 1, AML_SERIALIZED);
 944    Aml *crs = aml_resource_template();
 945
 946    irqs = 0;
 947    aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL,
 948                                  AML_ACTIVE_HIGH, AML_SHARED, &irqs, 1));
 949    aml_append(method, aml_name_decl("PRR0", crs));
 950
 951    aml_append(method,
 952        aml_create_dword_field(aml_name("PRR0"), aml_int(5), "PRRI"));
 953
 954    if (is_piix4) {
 955        if_ctx = aml_if(aml_lless(aml_arg(0), aml_int(0x80)));
 956        aml_append(if_ctx, aml_store(aml_arg(0), aml_name("PRRI")));
 957        aml_append(method, if_ctx);
 958    } else {
 959        aml_append(method,
 960            aml_store(aml_and(aml_arg(0), aml_int(0xF), NULL),
 961                      aml_name("PRRI")));
 962    }
 963
 964    aml_append(method, aml_return(aml_name("PRR0")));
 965    return method;
 966}
 967
 968/* _STA method - get status */
 969static Aml *build_irq_status_method(void)
 970{
 971    Aml *if_ctx;
 972    Aml *method = aml_method("IQST", 1, AML_NOTSERIALIZED);
 973
 974    if_ctx = aml_if(aml_and(aml_int(0x80), aml_arg(0), NULL));
 975    aml_append(if_ctx, aml_return(aml_int(0x09)));
 976    aml_append(method, if_ctx);
 977    aml_append(method, aml_return(aml_int(0x0B)));
 978    return method;
 979}
 980
 981static void build_piix4_pci0_int(Aml *table)
 982{
 983    Aml *dev;
 984    Aml *crs;
 985    Aml *field;
 986    Aml *method;
 987    uint32_t irqs;
 988    Aml *sb_scope = aml_scope("_SB");
 989    Aml *pci0_scope = aml_scope("PCI0");
 990
 991    aml_append(pci0_scope, build_prt(true));
 992    aml_append(sb_scope, pci0_scope);
 993
 994    field = aml_field("PCI0.ISA.P40C", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
 995    aml_append(field, aml_named_field("PRQ0", 8));
 996    aml_append(field, aml_named_field("PRQ1", 8));
 997    aml_append(field, aml_named_field("PRQ2", 8));
 998    aml_append(field, aml_named_field("PRQ3", 8));
 999    aml_append(sb_scope, field);
1000
1001    aml_append(sb_scope, build_irq_status_method());
1002    aml_append(sb_scope, build_iqcr_method(true));
1003
1004    aml_append(sb_scope, build_link_dev("LNKA", 0, aml_name("PRQ0")));
1005    aml_append(sb_scope, build_link_dev("LNKB", 1, aml_name("PRQ1")));
1006    aml_append(sb_scope, build_link_dev("LNKC", 2, aml_name("PRQ2")));
1007    aml_append(sb_scope, build_link_dev("LNKD", 3, aml_name("PRQ3")));
1008
1009    dev = aml_device("LNKS");
1010    {
1011        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C0F")));
1012        aml_append(dev, aml_name_decl("_UID", aml_int(4)));
1013
1014        crs = aml_resource_template();
1015        irqs = 9;
1016        aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL,
1017                                      AML_ACTIVE_HIGH, AML_SHARED,
1018                                      &irqs, 1));
1019        aml_append(dev, aml_name_decl("_PRS", crs));
1020
1021        /* The SCI cannot be disabled and is always attached to GSI 9,
1022         * so these are no-ops.  We only need this link to override the
1023         * polarity to active high and match the content of the MADT.
1024         */
1025        method = aml_method("_STA", 0, AML_NOTSERIALIZED);
1026        aml_append(method, aml_return(aml_int(0x0b)));
1027        aml_append(dev, method);
1028
1029        method = aml_method("_DIS", 0, AML_NOTSERIALIZED);
1030        aml_append(dev, method);
1031
1032        method = aml_method("_CRS", 0, AML_NOTSERIALIZED);
1033        aml_append(method, aml_return(aml_name("_PRS")));
1034        aml_append(dev, method);
1035
1036        method = aml_method("_SRS", 1, AML_NOTSERIALIZED);
1037        aml_append(dev, method);
1038    }
1039    aml_append(sb_scope, dev);
1040
1041    aml_append(table, sb_scope);
1042}
1043
1044static void append_q35_prt_entry(Aml *ctx, uint32_t nr, const char *name)
1045{
1046    int i;
1047    int head;
1048    Aml *pkg;
1049    char base = name[3] < 'E' ? 'A' : 'E';
1050    char *s = g_strdup(name);
1051    Aml *a_nr = aml_int((nr << 16) | 0xffff);
1052
1053    assert(strlen(s) == 4);
1054
1055    head = name[3] - base;
1056    for (i = 0; i < 4; i++) {
1057        if (head + i > 3) {
1058            head = i * -1;
1059        }
1060        s[3] = base + head + i;
1061        pkg = aml_package(4);
1062        aml_append(pkg, a_nr);
1063        aml_append(pkg, aml_int(i));
1064        aml_append(pkg, aml_name("%s", s));
1065        aml_append(pkg, aml_int(0));
1066        aml_append(ctx, pkg);
1067    }
1068    g_free(s);
1069}
1070
1071static Aml *build_q35_routing_table(const char *str)
1072{
1073    int i;
1074    Aml *pkg;
1075    char *name = g_strdup_printf("%s ", str);
1076
1077    pkg = aml_package(128);
1078    for (i = 0; i < 0x18; i++) {
1079            name[3] = 'E' + (i & 0x3);
1080            append_q35_prt_entry(pkg, i, name);
1081    }
1082
1083    name[3] = 'E';
1084    append_q35_prt_entry(pkg, 0x18, name);
1085
1086    /* INTA -> PIRQA for slot 25 - 31, see the default value of D<N>IR */
1087    for (i = 0x0019; i < 0x1e; i++) {
1088        name[3] = 'A';
1089        append_q35_prt_entry(pkg, i, name);
1090    }
1091
1092    /* PCIe->PCI bridge. use PIRQ[E-H] */
1093    name[3] = 'E';
1094    append_q35_prt_entry(pkg, 0x1e, name);
1095    name[3] = 'A';
1096    append_q35_prt_entry(pkg, 0x1f, name);
1097
1098    g_free(name);
1099    return pkg;
1100}
1101
1102static void build_q35_pci0_int(Aml *table)
1103{
1104    Aml *field;
1105    Aml *method;
1106    Aml *sb_scope = aml_scope("_SB");
1107    Aml *pci0_scope = aml_scope("PCI0");
1108
1109    /* Zero => PIC mode, One => APIC Mode */
1110    aml_append(table, aml_name_decl("PICF", aml_int(0)));
1111    method = aml_method("_PIC", 1, AML_NOTSERIALIZED);
1112    {
1113        aml_append(method, aml_store(aml_arg(0), aml_name("PICF")));
1114    }
1115    aml_append(table, method);
1116
1117    aml_append(pci0_scope,
1118        aml_name_decl("PRTP", build_q35_routing_table("LNK")));
1119    aml_append(pci0_scope,
1120        aml_name_decl("PRTA", build_q35_routing_table("GSI")));
1121
1122    method = aml_method("_PRT", 0, AML_NOTSERIALIZED);
1123    {
1124        Aml *if_ctx;
1125        Aml *else_ctx;
1126
1127        /* PCI IRQ routing table, example from ACPI 2.0a specification,
1128           section 6.2.8.1 */
1129        /* Note: we provide the same info as the PCI routing
1130           table of the Bochs BIOS */
1131        if_ctx = aml_if(aml_equal(aml_name("PICF"), aml_int(0)));
1132        aml_append(if_ctx, aml_return(aml_name("PRTP")));
1133        aml_append(method, if_ctx);
1134        else_ctx = aml_else();
1135        aml_append(else_ctx, aml_return(aml_name("PRTA")));
1136        aml_append(method, else_ctx);
1137    }
1138    aml_append(pci0_scope, method);
1139    aml_append(sb_scope, pci0_scope);
1140
1141    field = aml_field("PCI0.ISA.PIRQ", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
1142    aml_append(field, aml_named_field("PRQA", 8));
1143    aml_append(field, aml_named_field("PRQB", 8));
1144    aml_append(field, aml_named_field("PRQC", 8));
1145    aml_append(field, aml_named_field("PRQD", 8));
1146    aml_append(field, aml_reserved_field(0x20));
1147    aml_append(field, aml_named_field("PRQE", 8));
1148    aml_append(field, aml_named_field("PRQF", 8));
1149    aml_append(field, aml_named_field("PRQG", 8));
1150    aml_append(field, aml_named_field("PRQH", 8));
1151    aml_append(sb_scope, field);
1152
1153    aml_append(sb_scope, build_irq_status_method());
1154    aml_append(sb_scope, build_iqcr_method(false));
1155
1156    aml_append(sb_scope, build_link_dev("LNKA", 0, aml_name("PRQA")));
1157    aml_append(sb_scope, build_link_dev("LNKB", 1, aml_name("PRQB")));
1158    aml_append(sb_scope, build_link_dev("LNKC", 2, aml_name("PRQC")));
1159    aml_append(sb_scope, build_link_dev("LNKD", 3, aml_name("PRQD")));
1160    aml_append(sb_scope, build_link_dev("LNKE", 4, aml_name("PRQE")));
1161    aml_append(sb_scope, build_link_dev("LNKF", 5, aml_name("PRQF")));
1162    aml_append(sb_scope, build_link_dev("LNKG", 6, aml_name("PRQG")));
1163    aml_append(sb_scope, build_link_dev("LNKH", 7, aml_name("PRQH")));
1164
1165    aml_append(sb_scope, build_gsi_link_dev("GSIA", 0x10, 0x10));
1166    aml_append(sb_scope, build_gsi_link_dev("GSIB", 0x11, 0x11));
1167    aml_append(sb_scope, build_gsi_link_dev("GSIC", 0x12, 0x12));
1168    aml_append(sb_scope, build_gsi_link_dev("GSID", 0x13, 0x13));
1169    aml_append(sb_scope, build_gsi_link_dev("GSIE", 0x14, 0x14));
1170    aml_append(sb_scope, build_gsi_link_dev("GSIF", 0x15, 0x15));
1171    aml_append(sb_scope, build_gsi_link_dev("GSIG", 0x16, 0x16));
1172    aml_append(sb_scope, build_gsi_link_dev("GSIH", 0x17, 0x17));
1173
1174    aml_append(table, sb_scope);
1175}
1176
1177static Aml *build_q35_dram_controller(const AcpiMcfgInfo *mcfg)
1178{
1179    Aml *dev;
1180    Aml *resource_template;
1181
1182    /* DRAM controller */
1183    dev = aml_device("DRAC");
1184    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0C01")));
1185
1186    resource_template = aml_resource_template();
1187    if (mcfg->base + mcfg->size - 1 >= (1ULL << 32)) {
1188        aml_append(resource_template,
1189                   aml_qword_memory(AML_POS_DECODE,
1190                                    AML_MIN_FIXED,
1191                                    AML_MAX_FIXED,
1192                                    AML_NON_CACHEABLE,
1193                                    AML_READ_WRITE,
1194                                    0x0000000000000000,
1195                                    mcfg->base,
1196                                    mcfg->base + mcfg->size - 1,
1197                                    0x0000000000000000,
1198                                    mcfg->size));
1199    } else {
1200        aml_append(resource_template,
1201                   aml_dword_memory(AML_POS_DECODE,
1202                                    AML_MIN_FIXED,
1203                                    AML_MAX_FIXED,
1204                                    AML_NON_CACHEABLE,
1205                                    AML_READ_WRITE,
1206                                    0x0000000000000000,
1207                                    mcfg->base,
1208                                    mcfg->base + mcfg->size - 1,
1209                                    0x0000000000000000,
1210                                    mcfg->size));
1211    }
1212    aml_append(dev, aml_name_decl("_CRS", resource_template));
1213
1214    return dev;
1215}
1216
1217static void build_q35_isa_bridge(Aml *table)
1218{
1219    Aml *dev;
1220    Aml *scope;
1221
1222    scope =  aml_scope("_SB.PCI0");
1223    dev = aml_device("ISA");
1224    aml_append(dev, aml_name_decl("_ADR", aml_int(0x001F0000)));
1225
1226    /* ICH9 PCI to ISA irq remapping */
1227    aml_append(dev, aml_operation_region("PIRQ", AML_PCI_CONFIG,
1228                                         aml_int(0x60), 0x0C));
1229
1230    aml_append(scope, dev);
1231    aml_append(table, scope);
1232}
1233
1234static void build_piix4_isa_bridge(Aml *table)
1235{
1236    Aml *dev;
1237    Aml *scope;
1238
1239    scope =  aml_scope("_SB.PCI0");
1240    dev = aml_device("ISA");
1241    aml_append(dev, aml_name_decl("_ADR", aml_int(0x00010000)));
1242
1243    /* PIIX PCI to ISA irq remapping */
1244    aml_append(dev, aml_operation_region("P40C", AML_PCI_CONFIG,
1245                                         aml_int(0x60), 0x04));
1246
1247    aml_append(scope, dev);
1248    aml_append(table, scope);
1249}
1250
1251static void build_piix4_pci_hotplug(Aml *table)
1252{
1253    Aml *scope;
1254    Aml *field;
1255    Aml *method;
1256
1257    scope =  aml_scope("_SB.PCI0");
1258
1259    aml_append(scope,
1260        aml_operation_region("PCST", AML_SYSTEM_IO, aml_int(0xae00), 0x08));
1261    field = aml_field("PCST", AML_DWORD_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
1262    aml_append(field, aml_named_field("PCIU", 32));
1263    aml_append(field, aml_named_field("PCID", 32));
1264    aml_append(scope, field);
1265
1266    aml_append(scope,
1267        aml_operation_region("SEJ", AML_SYSTEM_IO, aml_int(0xae08), 0x04));
1268    field = aml_field("SEJ", AML_DWORD_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
1269    aml_append(field, aml_named_field("B0EJ", 32));
1270    aml_append(scope, field);
1271
1272    aml_append(scope,
1273        aml_operation_region("BNMR", AML_SYSTEM_IO, aml_int(0xae10), 0x08));
1274    field = aml_field("BNMR", AML_DWORD_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);
1275    aml_append(field, aml_named_field("BNUM", 32));
1276    aml_append(field, aml_named_field("PIDX", 32));
1277    aml_append(scope, field);
1278
1279    aml_append(scope, aml_mutex("BLCK", 0));
1280
1281    method = aml_method("PCEJ", 2, AML_NOTSERIALIZED);
1282    aml_append(method, aml_acquire(aml_name("BLCK"), 0xFFFF));
1283    aml_append(method, aml_store(aml_arg(0), aml_name("BNUM")));
1284    aml_append(method,
1285        aml_store(aml_shiftleft(aml_int(1), aml_arg(1)), aml_name("B0EJ")));
1286    aml_append(method, aml_release(aml_name("BLCK")));
1287    aml_append(method, aml_return(aml_int(0)));
1288    aml_append(scope, method);
1289
1290    method = aml_method("AIDX", 2, AML_NOTSERIALIZED);
1291    aml_append(method, aml_acquire(aml_name("BLCK"), 0xFFFF));
1292    aml_append(method, aml_store(aml_arg(0), aml_name("BNUM")));
1293    aml_append(method,
1294        aml_store(aml_shiftleft(aml_int(1), aml_arg(1)), aml_name("PIDX")));
1295    aml_append(method, aml_store(aml_name("PIDX"), aml_local(0)));
1296    aml_append(method, aml_release(aml_name("BLCK")));
1297    aml_append(method, aml_return(aml_local(0)));
1298    aml_append(scope, method);
1299
1300    aml_append(scope, aml_pci_device_dsm());
1301
1302    aml_append(table, scope);
1303}
1304
1305static Aml *build_q35_osc_method(void)
1306{
1307    Aml *if_ctx;
1308    Aml *if_ctx2;
1309    Aml *else_ctx;
1310    Aml *method;
1311    Aml *a_cwd1 = aml_name("CDW1");
1312    Aml *a_ctrl = aml_local(0);
1313
1314    method = aml_method("_OSC", 4, AML_NOTSERIALIZED);
1315    aml_append(method, aml_create_dword_field(aml_arg(3), aml_int(0), "CDW1"));
1316
1317    if_ctx = aml_if(aml_equal(
1318        aml_arg(0), aml_touuid("33DB4D5B-1FF7-401C-9657-7441C03DD766")));
1319    aml_append(if_ctx, aml_create_dword_field(aml_arg(3), aml_int(4), "CDW2"));
1320    aml_append(if_ctx, aml_create_dword_field(aml_arg(3), aml_int(8), "CDW3"));
1321
1322    aml_append(if_ctx, aml_store(aml_name("CDW3"), a_ctrl));
1323
1324    /*
1325     * Always allow native PME, AER (no dependencies)
1326     * Allow SHPC (PCI bridges can have SHPC controller)
1327     */
1328    aml_append(if_ctx, aml_and(a_ctrl, aml_int(0x1F), a_ctrl));
1329
1330    if_ctx2 = aml_if(aml_lnot(aml_equal(aml_arg(1), aml_int(1))));
1331    /* Unknown revision */
1332    aml_append(if_ctx2, aml_or(a_cwd1, aml_int(0x08), a_cwd1));
1333    aml_append(if_ctx, if_ctx2);
1334
1335    if_ctx2 = aml_if(aml_lnot(aml_equal(aml_name("CDW3"), a_ctrl)));
1336    /* Capabilities bits were masked */
1337    aml_append(if_ctx2, aml_or(a_cwd1, aml_int(0x10), a_cwd1));
1338    aml_append(if_ctx, if_ctx2);
1339
1340    /* Update DWORD3 in the buffer */
1341    aml_append(if_ctx, aml_store(a_ctrl, aml_name("CDW3")));
1342    aml_append(method, if_ctx);
1343
1344    else_ctx = aml_else();
1345    /* Unrecognized UUID */
1346    aml_append(else_ctx, aml_or(a_cwd1, aml_int(4), a_cwd1));
1347    aml_append(method, else_ctx);
1348
1349    aml_append(method, aml_return(aml_arg(3)));
1350    return method;
1351}
1352
1353static void build_smb0(Aml *table, I2CBus *smbus, int devnr, int func)
1354{
1355    Aml *scope = aml_scope("_SB.PCI0");
1356    Aml *dev = aml_device("SMB0");
1357
1358    aml_append(dev, aml_name_decl("_ADR", aml_int(devnr << 16 | func)));
1359    build_acpi_ipmi_devices(dev, BUS(smbus), "\\_SB.PCI0.SMB0");
1360    aml_append(scope, dev);
1361    aml_append(table, scope);
1362}
1363
1364static void
1365build_dsdt(GArray *table_data, BIOSLinker *linker,
1366           AcpiPmInfo *pm, AcpiMiscInfo *misc,
1367           Range *pci_hole, Range *pci_hole64, MachineState *machine)
1368{
1369    CrsRangeEntry *entry;
1370    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;
1371    CrsRangeSet crs_range_set;
1372    PCMachineState *pcms = PC_MACHINE(machine);
1373    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(machine);
1374    X86MachineState *x86ms = X86_MACHINE(machine);
1375    AcpiMcfgInfo mcfg;
1376    bool mcfg_valid = !!acpi_get_mcfg(&mcfg);
1377    uint32_t nr_mem = machine->ram_slots;
1378    int root_bus_limit = 0xFF;
1379    PCIBus *bus = NULL;
1380    TPMIf *tpm = tpm_find();
1381    int i;
1382    VMBusBridge *vmbus_bridge = vmbus_bridge_find();
1383
1384    dsdt = init_aml_allocator();
1385
1386    /* Reserve space for header */
1387    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));
1388
1389    build_dbg_aml(dsdt);
1390    if (misc->is_piix4) {
1391        sb_scope = aml_scope("_SB");
1392        dev = aml_device("PCI0");
1393        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));
1394        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));
1395        aml_append(dev, aml_name_decl("_UID", aml_int(pcmc->pci_root_uid)));
1396        aml_append(sb_scope, dev);
1397        aml_append(dsdt, sb_scope);
1398
1399        if (misc->has_hpet) {
1400            build_hpet_aml(dsdt);
1401        }
1402        build_piix4_isa_bridge(dsdt);
1403        build_isa_devices_aml(dsdt);
1404        if (pm->pcihp_bridge_en || pm->pcihp_root_en) {
1405            build_piix4_pci_hotplug(dsdt);
1406        }
1407        build_piix4_pci0_int(dsdt);
1408    } else {
1409        sb_scope = aml_scope("_SB");
1410        dev = aml_device("PCI0");
1411        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));
1412        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));
1413        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));
1414        aml_append(dev, aml_name_decl("_UID", aml_int(pcmc->pci_root_uid)));
1415        aml_append(dev, build_q35_osc_method());
1416        aml_append(sb_scope, dev);
1417        if (mcfg_valid) {
1418            aml_append(sb_scope, build_q35_dram_controller(&mcfg));
1419        }
1420
1421        if (pm->smi_on_cpuhp) {
1422            /* reserve SMI block resources, IO ports 0xB2, 0xB3 */
1423            dev = aml_device("PCI0.SMI0");
1424            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A06")));
1425            aml_append(dev, aml_name_decl("_UID", aml_string("SMI resources")));
1426            crs = aml_resource_template();
1427            aml_append(crs,
1428                aml_io(
1429                       AML_DECODE16,
1430                       ACPI_PORT_SMI_CMD,
1431                       ACPI_PORT_SMI_CMD,
1432                       1,
1433                       2)
1434            );
1435            aml_append(dev, aml_name_decl("_CRS", crs));
1436            aml_append(dev, aml_operation_region("SMIR", AML_SYSTEM_IO,
1437                aml_int(ACPI_PORT_SMI_CMD), 2));
1438            field = aml_field("SMIR", AML_BYTE_ACC, AML_NOLOCK,
1439                              AML_WRITE_AS_ZEROS);
1440            aml_append(field, aml_named_field("SMIC", 8));
1441            aml_append(field, aml_reserved_field(8));
1442            aml_append(dev, field);
1443            aml_append(sb_scope, dev);
1444        }
1445
1446        aml_append(dsdt, sb_scope);
1447
1448        if (misc->has_hpet) {
1449            build_hpet_aml(dsdt);
1450        }
1451        build_q35_isa_bridge(dsdt);
1452        build_isa_devices_aml(dsdt);
1453        build_q35_pci0_int(dsdt);
1454        if (pcms->smbus && !pcmc->do_not_add_smb_acpi) {
1455            build_smb0(dsdt, pcms->smbus, ICH9_SMB_DEV, ICH9_SMB_FUNC);
1456        }
1457    }
1458
1459    if (vmbus_bridge) {
1460        sb_scope = aml_scope("_SB");
1461        aml_append(sb_scope, build_vmbus_device_aml(vmbus_bridge));
1462        aml_append(dsdt, sb_scope);
1463    }
1464
1465    if (pcmc->legacy_cpu_hotplug) {
1466        build_legacy_cpu_hotplug_aml(dsdt, machine, pm->cpu_hp_io_base);
1467    } else {
1468        CPUHotplugFeatures opts = {
1469            .acpi_1_compatible = true, .has_legacy_cphp = true,
1470            .smi_path = pm->smi_on_cpuhp ? "\\_SB.PCI0.SMI0.SMIC" : NULL,
1471            .fw_unplugs_cpu = pm->smi_on_cpu_unplug,
1472        };
1473        build_cpus_aml(dsdt, machine, opts, pm->cpu_hp_io_base,
1474                       "\\_SB.PCI0", "\\_GPE._E02");
1475    }
1476
1477    if (pcms->memhp_io_base && nr_mem) {
1478        build_memory_hotplug_aml(dsdt, nr_mem, "\\_SB.PCI0",
1479                                 "\\_GPE._E03", AML_SYSTEM_IO,
1480                                 pcms->memhp_io_base);
1481    }
1482
1483    scope =  aml_scope("_GPE");
1484    {
1485        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));
1486
1487        if (misc->is_piix4 && (pm->pcihp_bridge_en || pm->pcihp_root_en)) {
1488            method = aml_method("_E01", 0, AML_NOTSERIALIZED);
1489            aml_append(method,
1490                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));
1491            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));
1492            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));
1493            aml_append(scope, method);
1494        }
1495
1496        if (machine->nvdimms_state->is_enabled) {
1497            method = aml_method("_E04", 0, AML_NOTSERIALIZED);
1498            aml_append(method, aml_notify(aml_name("\\_SB.NVDR"),
1499                                          aml_int(0x80)));
1500            aml_append(scope, method);
1501        }
1502    }
1503    aml_append(dsdt, scope);
1504
1505    crs_range_set_init(&crs_range_set);
1506    bus = PC_MACHINE(machine)->bus;
1507    if (bus) {
1508        QLIST_FOREACH(bus, &bus->child, sibling) {
1509            uint8_t bus_num = pci_bus_num(bus);
1510            uint8_t numa_node = pci_bus_numa_node(bus);
1511
1512            /* look only for expander root buses */
1513            if (!pci_bus_is_root(bus)) {
1514                continue;
1515            }
1516
1517            if (bus_num < root_bus_limit) {
1518                root_bus_limit = bus_num - 1;
1519            }
1520
1521            scope = aml_scope("\\_SB");
1522            dev = aml_device("PC%.02X", bus_num);
1523            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));
1524            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));
1525            if (pci_bus_is_express(bus)) {
1526                aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));
1527                aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));
1528                aml_append(dev, build_q35_osc_method());
1529            } else {
1530                aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));
1531            }
1532
1533            if (numa_node != NUMA_NODE_UNASSIGNED) {
1534                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));
1535            }
1536
1537            aml_append(dev, build_prt(false));
1538            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent), &crs_range_set,
1539                            0, 0, 0, 0);
1540            aml_append(dev, aml_name_decl("_CRS", crs));
1541            aml_append(scope, dev);
1542            aml_append(dsdt, scope);
1543        }
1544    }
1545
1546    /*
1547     * At this point crs_range_set has all the ranges used by pci
1548     * busses *other* than PCI0.  These ranges will be excluded from
1549     * the PCI0._CRS.  Add mmconfig to the set so it will be excluded
1550     * too.
1551     */
1552    if (mcfg_valid) {
1553        crs_range_insert(crs_range_set.mem_ranges,
1554                         mcfg.base, mcfg.base + mcfg.size - 1);
1555    }
1556
1557    scope = aml_scope("\\_SB.PCI0");
1558    /* build PCI0._CRS */
1559    crs = aml_resource_template();
1560    aml_append(crs,
1561        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,
1562                            0x0000, 0x0, root_bus_limit,
1563                            0x0000, root_bus_limit + 1));
1564    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));
1565
1566    aml_append(crs,
1567        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
1568                    AML_POS_DECODE, AML_ENTIRE_RANGE,
1569                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));
1570
1571    crs_replace_with_free_ranges(crs_range_set.io_ranges, 0x0D00, 0xFFFF);
1572    for (i = 0; i < crs_range_set.io_ranges->len; i++) {
1573        entry = g_ptr_array_index(crs_range_set.io_ranges, i);
1574        aml_append(crs,
1575            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,
1576                        AML_POS_DECODE, AML_ENTIRE_RANGE,
1577                        0x0000, entry->base, entry->limit,
1578                        0x0000, entry->limit - entry->base + 1));
1579    }
1580
1581    aml_append(crs,
1582        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
1583                         AML_CACHEABLE, AML_READ_WRITE,
1584                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));
1585
1586    crs_replace_with_free_ranges(crs_range_set.mem_ranges,
1587                                 range_lob(pci_hole),
1588                                 range_upb(pci_hole));
1589    for (i = 0; i < crs_range_set.mem_ranges->len; i++) {
1590        entry = g_ptr_array_index(crs_range_set.mem_ranges, i);
1591        aml_append(crs,
1592            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,
1593                             AML_NON_CACHEABLE, AML_READ_WRITE,
1594                             0, entry->base, entry->limit,
1595                             0, entry->limit - entry->base + 1));
1596    }
1597
1598    if (!range_is_empty(pci_hole64)) {
1599        crs_replace_with_free_ranges(crs_range_set.mem_64bit_ranges,
1600                                     range_lob(pci_hole64),
1601                                     range_upb(pci_hole64));
1602        for (i = 0; i < crs_range_set.mem_64bit_ranges->len; i++) {
1603            entry = g_ptr_array_index(crs_range_set.mem_64bit_ranges, i);
1604            aml_append(crs,
1605                       aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED,
1606                                        AML_MAX_FIXED,
1607                                        AML_CACHEABLE, AML_READ_WRITE,
1608                                        0, entry->base, entry->limit,
1609                                        0, entry->limit - entry->base + 1));
1610        }
1611    }
1612
1613    if (TPM_IS_TIS_ISA(tpm_find())) {
1614        aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,
1615                   TPM_TIS_ADDR_SIZE, AML_READ_WRITE));
1616    }
1617    aml_append(scope, aml_name_decl("_CRS", crs));
1618
1619    /* reserve GPE0 block resources */
1620    dev = aml_device("GPE0");
1621    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));
1622    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));
1623    /* device present, functioning, decoding, not shown in UI */
1624    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
1625    crs = aml_resource_template();
1626    aml_append(crs,
1627        aml_io(
1628               AML_DECODE16,
1629               pm->fadt.gpe0_blk.address,
1630               pm->fadt.gpe0_blk.address,
1631               1,
1632               pm->fadt.gpe0_blk.bit_width / 8)
1633    );
1634    aml_append(dev, aml_name_decl("_CRS", crs));
1635    aml_append(scope, dev);
1636
1637    crs_range_set_free(&crs_range_set);
1638
1639    /* reserve PCIHP resources */
1640    if (pm->pcihp_io_len && (pm->pcihp_bridge_en || pm->pcihp_root_en)) {
1641        dev = aml_device("PHPR");
1642        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));
1643        aml_append(dev,
1644            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));
1645        /* device present, functioning, decoding, not shown in UI */
1646        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
1647        crs = aml_resource_template();
1648        aml_append(crs,
1649            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,
1650                   pm->pcihp_io_len)
1651        );
1652        aml_append(dev, aml_name_decl("_CRS", crs));
1653        aml_append(scope, dev);
1654    }
1655    aml_append(dsdt, scope);
1656
1657    /*  create S3_ / S4_ / S5_ packages if necessary */
1658    scope = aml_scope("\\");
1659    if (!pm->s3_disabled) {
1660        pkg = aml_package(4);
1661        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */
1662        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */
1663        aml_append(pkg, aml_int(0)); /* reserved */
1664        aml_append(pkg, aml_int(0)); /* reserved */
1665        aml_append(scope, aml_name_decl("_S3", pkg));
1666    }
1667
1668    if (!pm->s4_disabled) {
1669        pkg = aml_package(4);
1670        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */
1671        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */
1672        aml_append(pkg, aml_int(pm->s4_val));
1673        aml_append(pkg, aml_int(0)); /* reserved */
1674        aml_append(pkg, aml_int(0)); /* reserved */
1675        aml_append(scope, aml_name_decl("_S4", pkg));
1676    }
1677
1678    pkg = aml_package(4);
1679    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */
1680    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */
1681    aml_append(pkg, aml_int(0)); /* reserved */
1682    aml_append(pkg, aml_int(0)); /* reserved */
1683    aml_append(scope, aml_name_decl("_S5", pkg));
1684    aml_append(dsdt, scope);
1685
1686    /* create fw_cfg node, unconditionally */
1687    {
1688        scope = aml_scope("\\_SB.PCI0");
1689        fw_cfg_add_acpi_dsdt(scope, x86ms->fw_cfg);
1690        aml_append(dsdt, scope);
1691    }
1692
1693    if (misc->applesmc_io_base) {
1694        scope = aml_scope("\\_SB.PCI0.ISA");
1695        dev = aml_device("SMC");
1696
1697        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));
1698        /* device present, functioning, decoding, not shown in UI */
1699        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));
1700
1701        crs = aml_resource_template();
1702        aml_append(crs,
1703            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,
1704                   0x01, APPLESMC_MAX_DATA_LENGTH)
1705        );
1706        aml_append(crs, aml_irq_no_flags(6));
1707        aml_append(dev, aml_name_decl("_CRS", crs));
1708
1709        aml_append(scope, dev);
1710        aml_append(dsdt, scope);
1711    }
1712
1713    if (misc->pvpanic_port) {
1714        scope = aml_scope("\\_SB.PCI0.ISA");
1715
1716        dev = aml_device("PEVT");
1717        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));
1718
1719        crs = aml_resource_template();
1720        aml_append(crs,
1721            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)
1722        );
1723        aml_append(dev, aml_name_decl("_CRS", crs));
1724
1725        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,
1726                                              aml_int(misc->pvpanic_port), 1));
1727        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);
1728        aml_append(field, aml_named_field("PEPT", 8));
1729        aml_append(dev, field);
1730
1731        /* device present, functioning, decoding, shown in UI */
1732        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
1733
1734        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);
1735        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));
1736        aml_append(method, aml_return(aml_local(0)));
1737        aml_append(dev, method);
1738
1739        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);
1740        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));
1741        aml_append(dev, method);
1742
1743        aml_append(scope, dev);
1744        aml_append(dsdt, scope);
1745    }
1746
1747    sb_scope = aml_scope("\\_SB");
1748    {
1749        Object *pci_host;
1750        PCIBus *bus = NULL;
1751
1752        pci_host = acpi_get_i386_pci_host();
1753        if (pci_host) {
1754            bus = PCI_HOST_BRIDGE(pci_host)->bus;
1755        }
1756
1757        if (bus) {
1758            Aml *scope = aml_scope("PCI0");
1759            /* Scan all PCI buses. Generate tables to support hotplug. */
1760            build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);
1761
1762            if (TPM_IS_TIS_ISA(tpm)) {
1763                if (misc->tpm_version == TPM_VERSION_2_0) {
1764                    dev = aml_device("TPM");
1765                    aml_append(dev, aml_name_decl("_HID",
1766                                                  aml_string("MSFT0101")));
1767                } else {
1768                    dev = aml_device("ISA.TPM");
1769                    aml_append(dev, aml_name_decl("_HID",
1770                                                  aml_eisaid("PNP0C31")));
1771                }
1772
1773                aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
1774                crs = aml_resource_template();
1775                aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,
1776                           TPM_TIS_ADDR_SIZE, AML_READ_WRITE));
1777                /*
1778                    FIXME: TPM_TIS_IRQ=5 conflicts with PNP0C0F irqs,
1779                    Rewrite to take IRQ from TPM device model and
1780                    fix default IRQ value there to use some unused IRQ
1781                 */
1782                /* aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ)); */
1783                aml_append(dev, aml_name_decl("_CRS", crs));
1784
1785                tpm_build_ppi_acpi(tpm, dev);
1786
1787                aml_append(scope, dev);
1788            }
1789
1790            aml_append(sb_scope, scope);
1791        }
1792    }
1793
1794    if (TPM_IS_CRB(tpm)) {
1795        dev = aml_device("TPM");
1796        aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
1797        crs = aml_resource_template();
1798        aml_append(crs, aml_memory32_fixed(TPM_CRB_ADDR_BASE,
1799                                           TPM_CRB_ADDR_SIZE, AML_READ_WRITE));
1800        aml_append(dev, aml_name_decl("_CRS", crs));
1801
1802        aml_append(dev, aml_name_decl("_STA", aml_int(0xf)));
1803
1804        tpm_build_ppi_acpi(tpm, dev);
1805
1806        aml_append(sb_scope, dev);
1807    }
1808
1809    aml_append(dsdt, sb_scope);
1810
1811    /* copy AML table into ACPI tables blob and patch header there */
1812    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);
1813    build_header(linker, table_data,
1814        (void *)(table_data->data + table_data->len - dsdt->buf->len),
1815                 "DSDT", dsdt->buf->len, 1, x86ms->oem_id, x86ms->oem_table_id);
1816    free_aml_allocator();
1817}
1818
1819static void
1820build_hpet(GArray *table_data, BIOSLinker *linker, const char *oem_id,
1821           const char *oem_table_id)
1822{
1823    Acpi20Hpet *hpet;
1824
1825    hpet = acpi_data_push(table_data, sizeof(*hpet));
1826    /* Note timer_block_id value must be kept in sync with value advertised by
1827     * emulated hpet
1828     */
1829    hpet->timer_block_id = cpu_to_le32(0x8086a201);
1830    hpet->addr.address = cpu_to_le64(HPET_BASE);
1831    build_header(linker, table_data,
1832                 (void *)hpet, "HPET", sizeof(*hpet), 1, oem_id, oem_table_id);
1833}
1834
1835static void
1836build_tpm_tcpa(GArray *table_data, BIOSLinker *linker, GArray *tcpalog,
1837               const char *oem_id, const char *oem_table_id)
1838{
1839    Acpi20Tcpa *tcpa = acpi_data_push(table_data, sizeof *tcpa);
1840    unsigned log_addr_size = sizeof(tcpa->log_area_start_address);
1841    unsigned log_addr_offset =
1842        (char *)&tcpa->log_area_start_address - table_data->data;
1843
1844    tcpa->platform_class = cpu_to_le16(TPM_TCPA_ACPI_CLASS_CLIENT);
1845    tcpa->log_area_minimum_length = cpu_to_le32(TPM_LOG_AREA_MINIMUM_SIZE);
1846    acpi_data_push(tcpalog, le32_to_cpu(tcpa->log_area_minimum_length));
1847
1848    bios_linker_loader_alloc(linker, ACPI_BUILD_TPMLOG_FILE, tcpalog, 1,
1849                             false /* high memory */);
1850
1851    /* log area start address to be filled by Guest linker */
1852    bios_linker_loader_add_pointer(linker,
1853        ACPI_BUILD_TABLE_FILE, log_addr_offset, log_addr_size,
1854        ACPI_BUILD_TPMLOG_FILE, 0);
1855
1856    build_header(linker, table_data,
1857                 (void *)tcpa, "TCPA", sizeof(*tcpa), 2, oem_id, oem_table_id);
1858}
1859
1860#define HOLE_640K_START  (640 * KiB)
1861#define HOLE_640K_END   (1 * MiB)
1862
1863static void
1864build_srat(GArray *table_data, BIOSLinker *linker, MachineState *machine)
1865{
1866    AcpiSystemResourceAffinityTable *srat;
1867    AcpiSratMemoryAffinity *numamem;
1868
1869    int i;
1870    int srat_start, numa_start, slots;
1871    uint64_t mem_len, mem_base, next_base;
1872    MachineClass *mc = MACHINE_GET_CLASS(machine);
1873    X86MachineState *x86ms = X86_MACHINE(machine);
1874    const CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);
1875    PCMachineState *pcms = PC_MACHINE(machine);
1876    ram_addr_t hotplugabble_address_space_size =
1877        object_property_get_int(OBJECT(pcms), PC_MACHINE_DEVMEM_REGION_SIZE,
1878                                NULL);
1879
1880    srat_start = table_data->len;
1881
1882    srat = acpi_data_push(table_data, sizeof *srat);
1883    srat->reserved1 = cpu_to_le32(1);
1884
1885    for (i = 0; i < apic_ids->len; i++) {
1886        int node_id = apic_ids->cpus[i].props.node_id;
1887        uint32_t apic_id = apic_ids->cpus[i].arch_id;
1888
1889        if (apic_id < 255) {
1890            AcpiSratProcessorAffinity *core;
1891
1892            core = acpi_data_push(table_data, sizeof *core);
1893            core->type = ACPI_SRAT_PROCESSOR_APIC;
1894            core->length = sizeof(*core);
1895            core->local_apic_id = apic_id;
1896            core->proximity_lo = node_id;
1897            memset(core->proximity_hi, 0, 3);
1898            core->local_sapic_eid = 0;
1899            core->flags = cpu_to_le32(1);
1900        } else {
1901            AcpiSratProcessorX2ApicAffinity *core;
1902
1903            core = acpi_data_push(table_data, sizeof *core);
1904            core->type = ACPI_SRAT_PROCESSOR_x2APIC;
1905            core->length = sizeof(*core);
1906            core->x2apic_id = cpu_to_le32(apic_id);
1907            core->proximity_domain = cpu_to_le32(node_id);
1908            core->flags = cpu_to_le32(1);
1909        }
1910    }
1911
1912
1913    /* the memory map is a bit tricky, it contains at least one hole
1914     * from 640k-1M and possibly another one from 3.5G-4G.
1915     */
1916    next_base = 0;
1917    numa_start = table_data->len;
1918
1919    for (i = 1; i < pcms->numa_nodes + 1; ++i) {
1920        mem_base = next_base;
1921        mem_len = pcms->node_mem[i - 1];
1922        next_base = mem_base + mem_len;
1923
1924        /* Cut out the 640K hole */
1925        if (mem_base <= HOLE_640K_START &&
1926            next_base > HOLE_640K_START) {
1927            mem_len -= next_base - HOLE_640K_START;
1928            if (mem_len > 0) {
1929                numamem = acpi_data_push(table_data, sizeof *numamem);
1930                build_srat_memory(numamem, mem_base, mem_len, i - 1,
1931                                  MEM_AFFINITY_ENABLED);
1932            }
1933
1934            /* Check for the rare case: 640K < RAM < 1M */
1935            if (next_base <= HOLE_640K_END) {
1936                next_base = HOLE_640K_END;
1937                continue;
1938            }
1939            mem_base = HOLE_640K_END;
1940            mem_len = next_base - HOLE_640K_END;
1941        }
1942
1943        /* Cut out the ACPI_PCI hole */
1944        if (mem_base <= x86ms->below_4g_mem_size &&
1945            next_base > x86ms->below_4g_mem_size) {
1946            mem_len -= next_base - x86ms->below_4g_mem_size;
1947            if (mem_len > 0) {
1948                numamem = acpi_data_push(table_data, sizeof *numamem);
1949                build_srat_memory(numamem, mem_base, mem_len, i - 1,
1950                                  MEM_AFFINITY_ENABLED);
1951            }
1952            mem_base = 1ULL << 32;
1953            mem_len = next_base - x86ms->below_4g_mem_size;
1954            next_base = mem_base + mem_len;
1955        }
1956
1957        if (mem_len > 0) {
1958            numamem = acpi_data_push(table_data, sizeof *numamem);
1959            build_srat_memory(numamem, mem_base, mem_len, i - 1,
1960                              MEM_AFFINITY_ENABLED);
1961        }
1962    }
1963
1964    if (machine->nvdimms_state->is_enabled) {
1965        nvdimm_build_srat(table_data);
1966    }
1967
1968    slots = (table_data->len - numa_start) / sizeof *numamem;
1969    for (; slots < pcms->numa_nodes + 2; slots++) {
1970        numamem = acpi_data_push(table_data, sizeof *numamem);
1971        build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS);
1972    }
1973
1974    /*
1975     * Entry is required for Windows to enable memory hotplug in OS
1976     * and for Linux to enable SWIOTLB when booted with less than
1977     * 4G of RAM. Windows works better if the entry sets proximity
1978     * to the highest NUMA node in the machine.
1979     * Memory devices may override proximity set by this entry,
1980     * providing _PXM method if necessary.
1981     */
1982    if (hotplugabble_address_space_size) {
1983        numamem = acpi_data_push(table_data, sizeof *numamem);
1984        build_srat_memory(numamem, machine->device_memory->base,
1985                          hotplugabble_address_space_size, pcms->numa_nodes - 1,
1986                          MEM_AFFINITY_HOTPLUGGABLE | MEM_AFFINITY_ENABLED);
1987    }
1988
1989    build_header(linker, table_data,
1990                 (void *)(table_data->data + srat_start),
1991                 "SRAT",
1992                 table_data->len - srat_start, 1, x86ms->oem_id,
1993                 x86ms->oem_table_id);
1994}
1995
1996/*
1997 * VT-d spec 8.1 DMA Remapping Reporting Structure
1998 * (version Oct. 2014 or later)
1999 */
2000static void
2001build_dmar_q35(GArray *table_data, BIOSLinker *linker, const char *oem_id,
2002               const char *oem_table_id)
2003{
2004    int dmar_start = table_data->len;
2005
2006    AcpiTableDmar *dmar;
2007    AcpiDmarHardwareUnit *drhd;
2008    AcpiDmarRootPortATS *atsr;
2009    uint8_t dmar_flags = 0;
2010    X86IOMMUState *iommu = x86_iommu_get_default();
2011    AcpiDmarDeviceScope *scope = NULL;
2012    /* Root complex IOAPIC use one path[0] only */
2013    size_t ioapic_scope_size = sizeof(*scope) + sizeof(scope->path[0]);
2014    IntelIOMMUState *intel_iommu = INTEL_IOMMU_DEVICE(iommu);
2015
2016    assert(iommu);
2017    if (x86_iommu_ir_supported(iommu)) {
2018        dmar_flags |= 0x1;      /* Flags: 0x1: INT_REMAP */
2019    }
2020
2021    dmar = acpi_data_push(table_data, sizeof(*dmar));
2022    dmar->host_address_width = intel_iommu->aw_bits - 1;
2023    dmar->flags = dmar_flags;
2024
2025    /* DMAR Remapping Hardware Unit Definition structure */
2026    drhd = acpi_data_push(table_data, sizeof(*drhd) + ioapic_scope_size);
2027    drhd->type = cpu_to_le16(ACPI_DMAR_TYPE_HARDWARE_UNIT);
2028    drhd->length = cpu_to_le16(sizeof(*drhd) + ioapic_scope_size);
2029    drhd->flags = ACPI_DMAR_INCLUDE_PCI_ALL;
2030    drhd->pci_segment = cpu_to_le16(0);
2031    drhd->address = cpu_to_le64(Q35_HOST_BRIDGE_IOMMU_ADDR);
2032
2033    /* Scope definition for the root-complex IOAPIC. See VT-d spec
2034     * 8.3.1 (version Oct. 2014 or later). */
2035    scope = &drhd->scope[0];
2036    scope->entry_type = 0x03;   /* Type: 0x03 for IOAPIC */
2037    scope->length = ioapic_scope_size;
2038    scope->enumeration_id = ACPI_BUILD_IOAPIC_ID;
2039    scope->bus = Q35_PSEUDO_BUS_PLATFORM;
2040    scope->path[0].device = PCI_SLOT(Q35_PSEUDO_DEVFN_IOAPIC);
2041    scope->path[0].function = PCI_FUNC(Q35_PSEUDO_DEVFN_IOAPIC);
2042
2043    if (iommu->dt_supported) {
2044        atsr = acpi_data_push(table_data, sizeof(*atsr));
2045        atsr->type = cpu_to_le16(ACPI_DMAR_TYPE_ATSR);
2046        atsr->length = cpu_to_le16(sizeof(*atsr));
2047        atsr->flags = ACPI_DMAR_ATSR_ALL_PORTS;
2048        atsr->pci_segment = cpu_to_le16(0);
2049    }
2050
2051    build_header(linker, table_data, (void *)(table_data->data + dmar_start),
2052                 "DMAR", table_data->len - dmar_start, 1, oem_id, oem_table_id);
2053}
2054
2055/*
2056 * Windows ACPI Emulated Devices Table
2057 * (Version 1.0 - April 6, 2009)
2058 * Spec: http://download.microsoft.com/download/7/E/7/7E7662CF-CBEA-470B-A97E-CE7CE0D98DC2/WAET.docx
2059 *
2060 * Helpful to speedup Windows guests and ignored by others.
2061 */
2062static void
2063build_waet(GArray *table_data, BIOSLinker *linker, const char *oem_id,
2064           const char *oem_table_id)
2065{
2066    int waet_start = table_data->len;
2067
2068    /* WAET header */
2069    acpi_data_push(table_data, sizeof(AcpiTableHeader));
2070    /*
2071     * Set "ACPI PM timer good" flag.
2072     *
2073     * Tells Windows guests that our ACPI PM timer is reliable in the
2074     * sense that guest can read it only once to obtain a reliable value.
2075     * Which avoids costly VMExits caused by guest re-reading it unnecessarily.
2076     */
2077    build_append_int_noprefix(table_data, 1 << 1 /* ACPI PM timer good */, 4);
2078
2079    build_header(linker, table_data, (void *)(table_data->data + waet_start),
2080                 "WAET", table_data->len - waet_start, 1, oem_id, oem_table_id);
2081}
2082
2083/*
2084 *   IVRS table as specified in AMD IOMMU Specification v2.62, Section 5.2
2085 *   accessible here http://support.amd.com/TechDocs/48882_IOMMU.pdf
2086 */
2087#define IOAPIC_SB_DEVID   (uint64_t)PCI_BUILD_BDF(0, PCI_DEVFN(0x14, 0))
2088
2089/*
2090 * Insert IVHD entry for device and recurse, insert alias, or insert range as
2091 * necessary for the PCI topology.
2092 */
2093static void
2094insert_ivhd(PCIBus *bus, PCIDevice *dev, void *opaque)
2095{
2096    GArray *table_data = opaque;
2097    uint32_t entry;
2098
2099    /* "Select" IVHD entry, type 0x2 */
2100    entry = PCI_BUILD_BDF(pci_bus_num(bus), dev->devfn) << 8 | 0x2;
2101    build_append_int_noprefix(table_data, entry, 4);
2102
2103    if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_BRIDGE)) {
2104        PCIBus *sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(dev));
2105        uint8_t sec = pci_bus_num(sec_bus);
2106        uint8_t sub = dev->config[PCI_SUBORDINATE_BUS];
2107
2108        if (pci_bus_is_express(sec_bus)) {
2109            /*
2110             * Walk the bus if there are subordinates, otherwise use a range
2111             * to cover an entire leaf bus.  We could potentially also use a
2112             * range for traversed buses, but we'd need to take care not to
2113             * create both Select and Range entries covering the same device.
2114             * This is easier and potentially more compact.
2115             *
2116             * An example bare metal system seems to use Select entries for
2117             * root ports without a slot (ie. built-ins) and Range entries
2118             * when there is a slot.  The same system also only hard-codes
2119             * the alias range for an onboard PCIe-to-PCI bridge, apparently
2120             * making no effort to support nested bridges.  We attempt to
2121             * be more thorough here.
2122             */
2123            if (sec == sub) { /* leaf bus */
2124                /* "Start of Range" IVHD entry, type 0x3 */
2125                entry = PCI_BUILD_BDF(sec, PCI_DEVFN(0, 0)) << 8 | 0x3;
2126                build_append_int_noprefix(table_data, entry, 4);
2127                /* "End of Range" IVHD entry, type 0x4 */
2128                entry = PCI_BUILD_BDF(sub, PCI_DEVFN(31, 7)) << 8 | 0x4;
2129                build_append_int_noprefix(table_data, entry, 4);
2130            } else {
2131                pci_for_each_device(sec_bus, sec, insert_ivhd, table_data);
2132            }
2133        } else {
2134            /*
2135             * If the secondary bus is conventional, then we need to create an
2136             * Alias range for everything downstream.  The range covers the
2137             * first devfn on the secondary bus to the last devfn on the
2138             * subordinate bus.  The alias target depends on legacy versus
2139             * express bridges, just as in pci_device_iommu_address_space().
2140             * DeviceIDa vs DeviceIDb as per the AMD IOMMU spec.
2141             */
2142            uint16_t dev_id_a, dev_id_b;
2143
2144            dev_id_a = PCI_BUILD_BDF(sec, PCI_DEVFN(0, 0));
2145
2146            if (pci_is_express(dev) &&
2147                pcie_cap_get_type(dev) == PCI_EXP_TYPE_PCI_BRIDGE) {
2148                dev_id_b = dev_id_a;
2149            } else {
2150                dev_id_b = PCI_BUILD_BDF(pci_bus_num(bus), dev->devfn);
2151            }
2152
2153            /* "Alias Start of Range" IVHD entry, type 0x43, 8 bytes */
2154            build_append_int_noprefix(table_data, dev_id_a << 8 | 0x43, 4);
2155            build_append_int_noprefix(table_data, dev_id_b << 8 | 0x0, 4);
2156
2157            /* "End of Range" IVHD entry, type 0x4 */
2158            entry = PCI_BUILD_BDF(sub, PCI_DEVFN(31, 7)) << 8 | 0x4;
2159            build_append_int_noprefix(table_data, entry, 4);
2160        }
2161    }
2162}
2163
2164/* For all PCI host bridges, walk and insert IVHD entries */
2165static int
2166ivrs_host_bridges(Object *obj, void *opaque)
2167{
2168    GArray *ivhd_blob = opaque;
2169
2170    if (object_dynamic_cast(obj, TYPE_PCI_HOST_BRIDGE)) {
2171        PCIBus *bus = PCI_HOST_BRIDGE(obj)->bus;
2172
2173        if (bus) {
2174            pci_for_each_device(bus, pci_bus_num(bus), insert_ivhd, ivhd_blob);
2175        }
2176    }
2177
2178    return 0;
2179}
2180
2181static void
2182build_amd_iommu(GArray *table_data, BIOSLinker *linker, const char *oem_id,
2183                const char *oem_table_id)
2184{
2185    int ivhd_table_len = 24;
2186    int iommu_start = table_data->len;
2187    AMDVIState *s = AMD_IOMMU_DEVICE(x86_iommu_get_default());
2188    GArray *ivhd_blob = g_array_new(false, true, 1);
2189
2190    /* IVRS header */
2191    acpi_data_push(table_data, sizeof(AcpiTableHeader));
2192    /* IVinfo - IO virtualization information common to all
2193     * IOMMU units in a system
2194     */
2195    build_append_int_noprefix(table_data, 40UL << 8/* PASize */, 4);
2196    /* reserved */
2197    build_append_int_noprefix(table_data, 0, 8);
2198
2199    /* IVHD definition - type 10h */
2200    build_append_int_noprefix(table_data, 0x10, 1);
2201    /* virtualization flags */
2202    build_append_int_noprefix(table_data,
2203                             (1UL << 0) | /* HtTunEn      */
2204                             (1UL << 4) | /* iotblSup     */
2205                             (1UL << 6) | /* PrefSup      */
2206                             (1UL << 7),  /* PPRSup       */
2207                             1);
2208
2209    /*
2210     * A PCI bus walk, for each PCI host bridge, is necessary to create a
2211     * complete set of IVHD entries.  Do this into a separate blob so that we
2212     * can calculate the total IVRS table length here and then append the new
2213     * blob further below.  Fall back to an entry covering all devices, which
2214     * is sufficient when no aliases are present.
2215     */
2216    object_child_foreach_recursive(object_get_root(),
2217                                   ivrs_host_bridges, ivhd_blob);
2218
2219    if (!ivhd_blob->len) {
2220        /*
2221         *   Type 1 device entry reporting all devices
2222         *   These are 4-byte device entries currently reporting the range of
2223         *   Refer to Spec - Table 95:IVHD Device Entry Type Codes(4-byte)
2224         */
2225        build_append_int_noprefix(ivhd_blob, 0x0000001, 4);
2226    }
2227
2228    ivhd_table_len += ivhd_blob->len;
2229
2230    /*
2231     * When interrupt remapping is supported, we add a special IVHD device
2232     * for type IO-APIC.
2233     */
2234    if (x86_iommu_ir_supported(x86_iommu_get_default())) {
2235        ivhd_table_len += 8;
2236    }
2237
2238    /* IVHD length */
2239    build_append_int_noprefix(table_data, ivhd_table_len, 2);
2240    /* DeviceID */
2241    build_append_int_noprefix(table_data, s->devid, 2);
2242    /* Capability offset */
2243    build_append_int_noprefix(table_data, s->capab_offset, 2);
2244    /* IOMMU base address */
2245    build_append_int_noprefix(table_data, s->mmio.addr, 8);
2246    /* PCI Segment Group */
2247    build_append_int_noprefix(table_data, 0, 2);
2248    /* IOMMU info */
2249    build_append_int_noprefix(table_data, 0, 2);
2250    /* IOMMU Feature Reporting */
2251    build_append_int_noprefix(table_data,
2252                             (48UL << 30) | /* HATS   */
2253                             (48UL << 28) | /* GATS   */
2254                             (1UL << 2)   | /* GTSup  */
2255                             (1UL << 6),    /* GASup  */
2256                             4);
2257
2258    /* IVHD entries as found above */
2259    g_array_append_vals(table_data, ivhd_blob->data, ivhd_blob->len);
2260    g_array_free(ivhd_blob, TRUE);
2261
2262    /*
2263     * Add a special IVHD device type.
2264     * Refer to spec - Table 95: IVHD device entry type codes
2265     *
2266     * Linux IOMMU driver checks for the special IVHD device (type IO-APIC).
2267     * See Linux kernel commit 'c2ff5cf5294bcbd7fa50f7d860e90a66db7e5059'
2268     */
2269    if (x86_iommu_ir_supported(x86_iommu_get_default())) {
2270        build_append_int_noprefix(table_data,
2271                                 (0x1ull << 56) |           /* type IOAPIC */
2272                                 (IOAPIC_SB_DEVID << 40) |  /* IOAPIC devid */
2273                                 0x48,                      /* special device */
2274                                 8);
2275    }
2276
2277    build_header(linker, table_data, (void *)(table_data->data + iommu_start),
2278                 "IVRS", table_data->len - iommu_start, 1, oem_id,
2279                 oem_table_id);
2280}
2281
2282typedef
2283struct AcpiBuildState {
2284    /* Copy of table in RAM (for patching). */
2285    MemoryRegion *table_mr;
2286    /* Is table patched? */
2287    uint8_t patched;
2288    void *rsdp;
2289    MemoryRegion *rsdp_mr;
2290    MemoryRegion *linker_mr;
2291} AcpiBuildState;
2292
2293static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
2294{
2295    Object *pci_host;
2296    QObject *o;
2297
2298    pci_host = acpi_get_i386_pci_host();
2299    g_assert(pci_host);
2300
2301    o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_BASE, NULL);
2302    if (!o) {
2303        return false;
2304    }
2305    mcfg->base = qnum_get_uint(qobject_to(QNum, o));
2306    qobject_unref(o);
2307    if (mcfg->base == PCIE_BASE_ADDR_UNMAPPED) {
2308        return false;
2309    }
2310
2311    o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_SIZE, NULL);
2312    assert(o);
2313    mcfg->size = qnum_get_uint(qobject_to(QNum, o));
2314    qobject_unref(o);
2315    return true;
2316}
2317
2318static
2319void acpi_build(AcpiBuildTables *tables, MachineState *machine)
2320{
2321    PCMachineState *pcms = PC_MACHINE(machine);
2322    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
2323    X86MachineState *x86ms = X86_MACHINE(machine);
2324    GArray *table_offsets;
2325    unsigned facs, dsdt, rsdt, fadt;
2326    AcpiPmInfo pm;
2327    AcpiMiscInfo misc;
2328    AcpiMcfgInfo mcfg;
2329    Range pci_hole, pci_hole64;
2330    uint8_t *u;
2331    size_t aml_len = 0;
2332    GArray *tables_blob = tables->table_data;
2333    AcpiSlicOem slic_oem = { .id = NULL, .table_id = NULL };
2334    Object *vmgenid_dev;
2335    char *oem_id;
2336    char *oem_table_id;
2337
2338    acpi_get_pm_info(machine, &pm);
2339    acpi_get_misc_info(&misc);
2340    acpi_get_pci_holes(&pci_hole, &pci_hole64);
2341    acpi_get_slic_oem(&slic_oem);
2342
2343    if (slic_oem.id) {
2344        oem_id = slic_oem.id;
2345    } else {
2346        oem_id = x86ms->oem_id;
2347    }
2348
2349    if (slic_oem.table_id) {
2350        oem_table_id = slic_oem.table_id;
2351    } else {
2352        oem_table_id = x86ms->oem_table_id;
2353    }
2354
2355    table_offsets = g_array_new(false, true /* clear */,
2356                                        sizeof(uint32_t));
2357    ACPI_BUILD_DPRINTF("init ACPI tables\n");
2358
2359    bios_linker_loader_alloc(tables->linker,
2360                             ACPI_BUILD_TABLE_FILE, tables_blob,
2361                             64 /* Ensure FACS is aligned */,
2362                             false /* high memory */);
2363
2364    /*
2365     * FACS is pointed to by FADT.
2366     * We place it first since it's the only table that has alignment
2367     * requirements.
2368     */
2369    facs = tables_blob->len;
2370    build_facs(tables_blob);
2371
2372    /* DSDT is pointed to by FADT */
2373    dsdt = tables_blob->len;
2374    build_dsdt(tables_blob, tables->linker, &pm, &misc,
2375               &pci_hole, &pci_hole64, machine);
2376
2377    /* Count the size of the DSDT and SSDT, we will need it for legacy
2378     * sizing of ACPI tables.
2379     */
2380    aml_len += tables_blob->len - dsdt;
2381
2382    /* ACPI tables pointed to by RSDT */
2383    fadt = tables_blob->len;
2384    acpi_add_table(table_offsets, tables_blob);
2385    pm.fadt.facs_tbl_offset = &facs;
2386    pm.fadt.dsdt_tbl_offset = &dsdt;
2387    pm.fadt.xdsdt_tbl_offset = &dsdt;
2388    build_fadt(tables_blob, tables->linker, &pm.fadt, oem_id, oem_table_id);
2389    aml_len += tables_blob->len - fadt;
2390
2391    acpi_add_table(table_offsets, tables_blob);
2392    acpi_build_madt(tables_blob, tables->linker, x86ms,
2393                    ACPI_DEVICE_IF(x86ms->acpi_dev), x86ms->oem_id,
2394                    x86ms->oem_table_id);
2395
2396    vmgenid_dev = find_vmgenid_dev();
2397    if (vmgenid_dev) {
2398        acpi_add_table(table_offsets, tables_blob);
2399        vmgenid_build_acpi(VMGENID(vmgenid_dev), tables_blob,
2400                           tables->vmgenid, tables->linker, x86ms->oem_id);
2401    }
2402
2403    if (misc.has_hpet) {
2404        acpi_add_table(table_offsets, tables_blob);
2405        build_hpet(tables_blob, tables->linker, x86ms->oem_id,
2406                   x86ms->oem_table_id);
2407    }
2408    if (misc.tpm_version != TPM_VERSION_UNSPEC) {
2409        if (misc.tpm_version == TPM_VERSION_1_2) {
2410            acpi_add_table(table_offsets, tables_blob);
2411            build_tpm_tcpa(tables_blob, tables->linker, tables->tcpalog,
2412                           x86ms->oem_id, x86ms->oem_table_id);
2413        } else { /* TPM_VERSION_2_0 */
2414            acpi_add_table(table_offsets, tables_blob);
2415            build_tpm2(tables_blob, tables->linker, tables->tcpalog,
2416                       x86ms->oem_id, x86ms->oem_table_id);
2417        }
2418    }
2419    if (pcms->numa_nodes) {
2420        acpi_add_table(table_offsets, tables_blob);
2421        build_srat(tables_blob, tables->linker, machine);
2422        if (machine->numa_state->have_numa_distance) {
2423            acpi_add_table(table_offsets, tables_blob);
2424            build_slit(tables_blob, tables->linker, machine, x86ms->oem_id,
2425                       x86ms->oem_table_id);
2426        }
2427        if (machine->numa_state->hmat_enabled) {
2428            acpi_add_table(table_offsets, tables_blob);
2429            build_hmat(tables_blob, tables->linker, machine->numa_state,
2430                       x86ms->oem_id, x86ms->oem_table_id);
2431        }
2432    }
2433    if (acpi_get_mcfg(&mcfg)) {
2434        acpi_add_table(table_offsets, tables_blob);
2435        build_mcfg(tables_blob, tables->linker, &mcfg, x86ms->oem_id,
2436                   x86ms->oem_table_id);
2437    }
2438    if (x86_iommu_get_default()) {
2439        IommuType IOMMUType = x86_iommu_get_type();
2440        if (IOMMUType == TYPE_AMD) {
2441            acpi_add_table(table_offsets, tables_blob);
2442            build_amd_iommu(tables_blob, tables->linker, x86ms->oem_id,
2443                            x86ms->oem_table_id);
2444        } else if (IOMMUType == TYPE_INTEL) {
2445            acpi_add_table(table_offsets, tables_blob);
2446            build_dmar_q35(tables_blob, tables->linker, x86ms->oem_id,
2447                           x86ms->oem_table_id);
2448        }
2449    }
2450    if (machine->nvdimms_state->is_enabled) {
2451        nvdimm_build_acpi(table_offsets, tables_blob, tables->linker,
2452                          machine->nvdimms_state, machine->ram_slots,
2453                          x86ms->oem_id, x86ms->oem_table_id);
2454    }
2455
2456    acpi_add_table(table_offsets, tables_blob);
2457    build_waet(tables_blob, tables->linker, x86ms->oem_id, x86ms->oem_table_id);
2458
2459    /* Add tables supplied by user (if any) */
2460    for (u = acpi_table_first(); u; u = acpi_table_next(u)) {
2461        unsigned len = acpi_table_len(u);
2462
2463        acpi_add_table(table_offsets, tables_blob);
2464        g_array_append_vals(tables_blob, u, len);
2465    }
2466
2467    /* RSDT is pointed to by RSDP */
2468    rsdt = tables_blob->len;
2469    build_rsdt(tables_blob, tables->linker, table_offsets,
2470               oem_id, oem_table_id);
2471
2472    /* RSDP is in FSEG memory, so allocate it separately */
2473    {
2474        AcpiRsdpData rsdp_data = {
2475            .revision = 0,
2476            .oem_id = x86ms->oem_id,
2477            .xsdt_tbl_offset = NULL,
2478            .rsdt_tbl_offset = &rsdt,
2479        };
2480        build_rsdp(tables->rsdp, tables->linker, &rsdp_data);
2481        if (!pcmc->rsdp_in_ram) {
2482            /* We used to allocate some extra space for RSDP revision 2 but
2483             * only used the RSDP revision 0 space. The extra bytes were
2484             * zeroed out and not used.
2485             * Here we continue wasting those extra 16 bytes to make sure we
2486             * don't break migration for machine types 2.2 and older due to
2487             * RSDP blob size mismatch.
2488             */
2489            build_append_int_noprefix(tables->rsdp, 0, 16);
2490        }
2491    }
2492
2493    /* We'll expose it all to Guest so we want to reduce
2494     * chance of size changes.
2495     *
2496     * We used to align the tables to 4k, but of course this would
2497     * too simple to be enough.  4k turned out to be too small an
2498     * alignment very soon, and in fact it is almost impossible to
2499     * keep the table size stable for all (max_cpus, max_memory_slots)
2500     * combinations.  So the table size is always 64k for pc-i440fx-2.1
2501     * and we give an error if the table grows beyond that limit.
2502     *
2503     * We still have the problem of migrating from "-M pc-i440fx-2.0".  For
2504     * that, we exploit the fact that QEMU 2.1 generates _smaller_ tables
2505     * than 2.0 and we can always pad the smaller tables with zeros.  We can
2506     * then use the exact size of the 2.0 tables.
2507     *
2508     * All this is for PIIX4, since QEMU 2.0 didn't support Q35 migration.
2509     */
2510    if (pcmc->legacy_acpi_table_size) {
2511        /* Subtracting aml_len gives the size of fixed tables.  Then add the
2512         * size of the PIIX4 DSDT/SSDT in QEMU 2.0.
2513         */
2514        int legacy_aml_len =
2515            pcmc->legacy_acpi_table_size +
2516            ACPI_BUILD_LEGACY_CPU_AML_SIZE * x86ms->apic_id_limit;
2517        int legacy_table_size =
2518            ROUND_UP(tables_blob->len - aml_len + legacy_aml_len,
2519                     ACPI_BUILD_ALIGN_SIZE);
2520        if (tables_blob->len > legacy_table_size) {
2521            /* Should happen only with PCI bridges and -M pc-i440fx-2.0.  */
2522            warn_report("ACPI table size %u exceeds %d bytes,"
2523                        " migration may not work",
2524                        tables_blob->len, legacy_table_size);
2525            error_printf("Try removing CPUs, NUMA nodes, memory slots"
2526                         " or PCI bridges.");
2527        }
2528        g_array_set_size(tables_blob, legacy_table_size);
2529    } else {
2530        /* Make sure we have a buffer in case we need to resize the tables. */
2531        if (tables_blob->len > ACPI_BUILD_TABLE_SIZE / 2) {
2532            /* As of QEMU 2.1, this fires with 160 VCPUs and 255 memory slots.  */
2533            warn_report("ACPI table size %u exceeds %d bytes,"
2534                        " migration may not work",
2535                        tables_blob->len, ACPI_BUILD_TABLE_SIZE / 2);
2536            error_printf("Try removing CPUs, NUMA nodes, memory slots"
2537                         " or PCI bridges.");
2538        }
2539        acpi_align_size(tables_blob, ACPI_BUILD_TABLE_SIZE);
2540    }
2541
2542    acpi_align_size(tables->linker->cmd_blob, ACPI_BUILD_ALIGN_SIZE);
2543
2544    /* Cleanup memory that's no longer used. */
2545    g_array_free(table_offsets, true);
2546}
2547
2548static void acpi_ram_update(MemoryRegion *mr, GArray *data)
2549{
2550    uint32_t size = acpi_data_len(data);
2551
2552    /* Make sure RAM size is correct - in case it got changed e.g. by migration */
2553    memory_region_ram_resize(mr, size, &error_abort);
2554
2555    memcpy(memory_region_get_ram_ptr(mr), data->data, size);
2556    memory_region_set_dirty(mr, 0, size);
2557}
2558
2559static void acpi_build_update(void *build_opaque)
2560{
2561    AcpiBuildState *build_state = build_opaque;
2562    AcpiBuildTables tables;
2563
2564    /* No state to update or already patched? Nothing to do. */
2565    if (!build_state || build_state->patched) {
2566        return;
2567    }
2568    build_state->patched = 1;
2569
2570    acpi_build_tables_init(&tables);
2571
2572    acpi_build(&tables, MACHINE(qdev_get_machine()));
2573
2574    acpi_ram_update(build_state->table_mr, tables.table_data);
2575
2576    if (build_state->rsdp) {
2577        memcpy(build_state->rsdp, tables.rsdp->data, acpi_data_len(tables.rsdp));
2578    } else {
2579        acpi_ram_update(build_state->rsdp_mr, tables.rsdp);
2580    }
2581
2582    acpi_ram_update(build_state->linker_mr, tables.linker->cmd_blob);
2583    acpi_build_tables_cleanup(&tables, true);
2584}
2585
2586static void acpi_build_reset(void *build_opaque)
2587{
2588    AcpiBuildState *build_state = build_opaque;
2589    build_state->patched = 0;
2590}
2591
2592static const VMStateDescription vmstate_acpi_build = {
2593    .name = "acpi_build",
2594    .version_id = 1,
2595    .minimum_version_id = 1,
2596    .fields = (VMStateField[]) {
2597        VMSTATE_UINT8(patched, AcpiBuildState),
2598        VMSTATE_END_OF_LIST()
2599    },
2600};
2601
2602void acpi_setup(void)
2603{
2604    PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
2605    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
2606    X86MachineState *x86ms = X86_MACHINE(pcms);
2607    AcpiBuildTables tables;
2608    AcpiBuildState *build_state;
2609    Object *vmgenid_dev;
2610    TPMIf *tpm;
2611    static FwCfgTPMConfig tpm_config;
2612
2613    if (!x86ms->fw_cfg) {
2614        ACPI_BUILD_DPRINTF("No fw cfg. Bailing out.\n");
2615        return;
2616    }
2617
2618    if (!pcms->acpi_build_enabled) {
2619        ACPI_BUILD_DPRINTF("ACPI build disabled. Bailing out.\n");
2620        return;
2621    }
2622
2623    if (!x86_machine_is_acpi_enabled(X86_MACHINE(pcms))) {
2624        ACPI_BUILD_DPRINTF("ACPI disabled. Bailing out.\n");
2625        return;
2626    }
2627
2628    build_state = g_malloc0(sizeof *build_state);
2629
2630    acpi_build_tables_init(&tables);
2631    acpi_build(&tables, MACHINE(pcms));
2632
2633    /* Now expose it all to Guest */
2634    build_state->table_mr = acpi_add_rom_blob(acpi_build_update,
2635                                              build_state, tables.table_data,
2636                                              ACPI_BUILD_TABLE_FILE);
2637    assert(build_state->table_mr != NULL);
2638
2639    build_state->linker_mr =
2640        acpi_add_rom_blob(acpi_build_update, build_state,
2641                          tables.linker->cmd_blob, ACPI_BUILD_LOADER_FILE);
2642
2643    fw_cfg_add_file(x86ms->fw_cfg, ACPI_BUILD_TPMLOG_FILE,
2644                    tables.tcpalog->data, acpi_data_len(tables.tcpalog));
2645
2646    tpm = tpm_find();
2647    if (tpm && object_property_get_bool(OBJECT(tpm), "ppi", &error_abort)) {
2648        tpm_config = (FwCfgTPMConfig) {
2649            .tpmppi_address = cpu_to_le32(TPM_PPI_ADDR_BASE),
2650            .tpm_version = tpm_get_version(tpm),
2651            .tpmppi_version = TPM_PPI_VERSION_1_30
2652        };
2653        fw_cfg_add_file(x86ms->fw_cfg, "etc/tpm/config",
2654                        &tpm_config, sizeof tpm_config);
2655    }
2656
2657    vmgenid_dev = find_vmgenid_dev();
2658    if (vmgenid_dev) {
2659        vmgenid_add_fw_cfg(VMGENID(vmgenid_dev), x86ms->fw_cfg,
2660                           tables.vmgenid);
2661    }
2662
2663    if (!pcmc->rsdp_in_ram) {
2664        /*
2665         * Keep for compatibility with old machine types.
2666         * Though RSDP is small, its contents isn't immutable, so
2667         * we'll update it along with the rest of tables on guest access.
2668         */
2669        uint32_t rsdp_size = acpi_data_len(tables.rsdp);
2670
2671        build_state->rsdp = g_memdup(tables.rsdp->data, rsdp_size);
2672        fw_cfg_add_file_callback(x86ms->fw_cfg, ACPI_BUILD_RSDP_FILE,
2673                                 acpi_build_update, NULL, build_state,
2674                                 build_state->rsdp, rsdp_size, true);
2675        build_state->rsdp_mr = NULL;
2676    } else {
2677        build_state->rsdp = NULL;
2678        build_state->rsdp_mr = acpi_add_rom_blob(acpi_build_update,
2679                                                 build_state, tables.rsdp,
2680                                                 ACPI_BUILD_RSDP_FILE);
2681    }
2682
2683    qemu_register_reset(acpi_build_reset, build_state);
2684    acpi_build_reset(build_state);
2685    vmstate_register(NULL, 0, &vmstate_acpi_build, build_state);
2686
2687    /* Cleanup tables but don't free the memory: we track it
2688     * in build_state.
2689     */
2690    acpi_build_tables_cleanup(&tables, false);
2691}
2692