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