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