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