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