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