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