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