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