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