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