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