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