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