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