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