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