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