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