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