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