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