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