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