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