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