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