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