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