xref: /openbmc/qemu/hw/arm/virt-acpi-build.c (revision 767df742fbc9e6cc06e9309685407beb2565c272)
1 /* Support for generating ACPI tables and passing them to Guests
2  *
3  * ARM virt ACPI generation
4  *
5  * Copyright (C) 2008-2010  Kevin O'Connor <kevin@koconnor.net>
6  * Copyright (C) 2006 Fabrice Bellard
7  * Copyright (C) 2013 Red Hat Inc
8  *
9  * Author: Michael S. Tsirkin <mst@redhat.com>
10  *
11  * Copyright (c) 2015 HUAWEI TECHNOLOGIES CO.,LTD.
12  *
13  * Author: Shannon Zhao <zhaoshenglong@huawei.com>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19 
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24 
25  * You should have received a copy of the GNU General Public License along
26  * with this program; if not, see <http://www.gnu.org/licenses/>.
27  */
28 
29 #include "qemu/osdep.h"
30 #include "qapi/error.h"
31 #include "qemu/bitmap.h"
32 #include "qemu/error-report.h"
33 #include "trace.h"
34 #include "hw/core/cpu.h"
35 #include "hw/acpi/acpi-defs.h"
36 #include "hw/acpi/acpi.h"
37 #include "hw/nvram/fw_cfg_acpi.h"
38 #include "hw/acpi/bios-linker-loader.h"
39 #include "hw/acpi/aml-build.h"
40 #include "hw/acpi/utils.h"
41 #include "hw/acpi/pci.h"
42 #include "hw/acpi/memory_hotplug.h"
43 #include "hw/acpi/generic_event_device.h"
44 #include "hw/acpi/tpm.h"
45 #include "hw/acpi/hmat.h"
46 #include "hw/pci/pcie_host.h"
47 #include "hw/pci/pci.h"
48 #include "hw/pci/pci_bus.h"
49 #include "hw/pci-host/gpex.h"
50 #include "hw/arm/virt.h"
51 #include "hw/intc/arm_gicv3_its_common.h"
52 #include "hw/mem/nvdimm.h"
53 #include "hw/platform-bus.h"
54 #include "system/numa.h"
55 #include "system/reset.h"
56 #include "system/tpm.h"
57 #include "migration/vmstate.h"
58 #include "hw/acpi/ghes.h"
59 #include "hw/acpi/viot.h"
60 #include "hw/virtio/virtio-acpi.h"
61 #include "target/arm/multiprocessing.h"
62 
63 #define ARM_SPI_BASE 32
64 
65 #define ACPI_BUILD_TABLE_SIZE             0x20000
66 
67 static void acpi_dsdt_add_cpus(Aml *scope, VirtMachineState *vms)
68 {
69     MachineState *ms = MACHINE(vms);
70     uint16_t i;
71 
72     for (i = 0; i < ms->smp.cpus; i++) {
73         Aml *dev = aml_device("C%.03X", i);
74         aml_append(dev, aml_name_decl("_HID", aml_string("ACPI0007")));
75         aml_append(dev, aml_name_decl("_UID", aml_int(i)));
76         aml_append(scope, dev);
77     }
78 }
79 
80 static void acpi_dsdt_add_uart(Aml *scope, const MemMapEntry *uart_memmap,
81                                uint32_t uart_irq, int uartidx)
82 {
83     Aml *dev = aml_device("COM%d", uartidx);
84     aml_append(dev, aml_name_decl("_HID", aml_string("ARMH0011")));
85     aml_append(dev, aml_name_decl("_UID", aml_int(uartidx)));
86 
87     Aml *crs = aml_resource_template();
88     aml_append(crs, aml_memory32_fixed(uart_memmap->base,
89                                        uart_memmap->size, AML_READ_WRITE));
90     aml_append(crs,
91                aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,
92                              AML_EXCLUSIVE, &uart_irq, 1));
93     aml_append(dev, aml_name_decl("_CRS", crs));
94 
95     aml_append(scope, dev);
96 }
97 
98 static void acpi_dsdt_add_flash(Aml *scope, const MemMapEntry *flash_memmap)
99 {
100     Aml *dev, *crs;
101     hwaddr base = flash_memmap->base;
102     hwaddr size = flash_memmap->size / 2;
103 
104     dev = aml_device("FLS0");
105     aml_append(dev, aml_name_decl("_HID", aml_string("LNRO0015")));
106     aml_append(dev, aml_name_decl("_UID", aml_int(0)));
107 
108     crs = aml_resource_template();
109     aml_append(crs, aml_memory32_fixed(base, size, AML_READ_WRITE));
110     aml_append(dev, aml_name_decl("_CRS", crs));
111     aml_append(scope, dev);
112 
113     dev = aml_device("FLS1");
114     aml_append(dev, aml_name_decl("_HID", aml_string("LNRO0015")));
115     aml_append(dev, aml_name_decl("_UID", aml_int(1)));
116     crs = aml_resource_template();
117     aml_append(crs, aml_memory32_fixed(base + size, size, AML_READ_WRITE));
118     aml_append(dev, aml_name_decl("_CRS", crs));
119     aml_append(scope, dev);
120 }
121 
122 static void acpi_dsdt_add_pci(Aml *scope, const MemMapEntry *memmap,
123                               uint32_t irq, VirtMachineState *vms)
124 {
125     int ecam_id = VIRT_ECAM_ID(vms->highmem_ecam);
126     struct GPEXConfig cfg = {
127         .mmio32 = memmap[VIRT_PCIE_MMIO],
128         .pio    = memmap[VIRT_PCIE_PIO],
129         .ecam   = memmap[ecam_id],
130         .irq    = irq,
131         .bus    = vms->bus,
132     };
133 
134     if (vms->highmem_mmio) {
135         cfg.mmio64 = memmap[VIRT_HIGH_PCIE_MMIO];
136     }
137 
138     acpi_dsdt_add_gpex(scope, &cfg);
139 }
140 
141 static void acpi_dsdt_add_gpio(Aml *scope, const MemMapEntry *gpio_memmap,
142                                            uint32_t gpio_irq)
143 {
144     Aml *dev = aml_device("GPO0");
145     aml_append(dev, aml_name_decl("_HID", aml_string("ARMH0061")));
146     aml_append(dev, aml_name_decl("_UID", aml_int(0)));
147 
148     Aml *crs = aml_resource_template();
149     aml_append(crs, aml_memory32_fixed(gpio_memmap->base, gpio_memmap->size,
150                                        AML_READ_WRITE));
151     aml_append(crs, aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,
152                                   AML_EXCLUSIVE, &gpio_irq, 1));
153     aml_append(dev, aml_name_decl("_CRS", crs));
154 
155     Aml *aei = aml_resource_template();
156 
157     const uint32_t pin = GPIO_PIN_POWER_BUTTON;
158     aml_append(aei, aml_gpio_int(AML_CONSUMER, AML_EDGE, AML_ACTIVE_HIGH,
159                                  AML_EXCLUSIVE, AML_PULL_UP, 0, &pin, 1,
160                                  "GPO0", NULL, 0));
161     aml_append(dev, aml_name_decl("_AEI", aei));
162 
163     /* _E03 is handle for power button */
164     Aml *method = aml_method("_E03", 0, AML_NOTSERIALIZED);
165     aml_append(method, aml_notify(aml_name(ACPI_POWER_BUTTON_DEVICE),
166                                   aml_int(0x80)));
167     aml_append(dev, method);
168     aml_append(scope, dev);
169 }
170 
171 #ifdef CONFIG_TPM
172 static void acpi_dsdt_add_tpm(Aml *scope, VirtMachineState *vms)
173 {
174     PlatformBusDevice *pbus = PLATFORM_BUS_DEVICE(vms->platform_bus_dev);
175     hwaddr pbus_base = vms->memmap[VIRT_PLATFORM_BUS].base;
176     SysBusDevice *sbdev = SYS_BUS_DEVICE(tpm_find());
177     MemoryRegion *sbdev_mr;
178     hwaddr tpm_base;
179 
180     if (!sbdev) {
181         return;
182     }
183 
184     tpm_base = platform_bus_get_mmio_addr(pbus, sbdev, 0);
185     assert(tpm_base != -1);
186 
187     tpm_base += pbus_base;
188 
189     sbdev_mr = sysbus_mmio_get_region(sbdev, 0);
190 
191     Aml *dev = aml_device("TPM0");
192     aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
193     aml_append(dev, aml_name_decl("_STR", aml_string("TPM 2.0 Device")));
194     aml_append(dev, aml_name_decl("_UID", aml_int(0)));
195 
196     Aml *crs = aml_resource_template();
197     aml_append(crs,
198                aml_memory32_fixed(tpm_base,
199                                   (uint32_t)memory_region_size(sbdev_mr),
200                                   AML_READ_WRITE));
201     aml_append(dev, aml_name_decl("_CRS", crs));
202     aml_append(scope, dev);
203 }
204 #endif
205 
206 #define ID_MAPPING_ENTRY_SIZE 20
207 #define SMMU_V3_ENTRY_SIZE 68
208 #define ROOT_COMPLEX_ENTRY_SIZE 36
209 #define IORT_NODE_OFFSET 48
210 
211 /*
212  * Append an ID mapping entry as described by "Table 4 ID mapping format" in
213  * "IO Remapping Table System Software on ARM Platforms", Chapter 3.
214  * Document number: ARM DEN 0049E.f, Apr 2024
215  *
216  * Note that @id_count gets internally subtracted by one, following the spec.
217  */
218 static void build_iort_id_mapping(GArray *table_data, uint32_t input_base,
219                                   uint32_t id_count, uint32_t out_ref)
220 {
221     build_append_int_noprefix(table_data, input_base, 4); /* Input base */
222     /* Number of IDs - The number of IDs in the range minus one */
223     build_append_int_noprefix(table_data, id_count - 1, 4);
224     build_append_int_noprefix(table_data, input_base, 4); /* Output base */
225     build_append_int_noprefix(table_data, out_ref, 4); /* Output Reference */
226     /* Flags */
227     build_append_int_noprefix(table_data, 0 /* Single mapping (disabled) */, 4);
228 }
229 
230 struct AcpiIortIdMapping {
231     uint32_t input_base;
232     uint32_t id_count;
233 };
234 typedef struct AcpiIortIdMapping AcpiIortIdMapping;
235 
236 /* Build the iort ID mapping to SMMUv3 for a given PCI host bridge */
237 static int
238 iort_host_bridges(Object *obj, void *opaque)
239 {
240     GArray *idmap_blob = opaque;
241 
242     if (object_dynamic_cast(obj, TYPE_PCI_HOST_BRIDGE)) {
243         PCIBus *bus = PCI_HOST_BRIDGE(obj)->bus;
244 
245         if (bus && !pci_bus_bypass_iommu(bus)) {
246             int min_bus, max_bus;
247 
248             pci_bus_range(bus, &min_bus, &max_bus);
249 
250             AcpiIortIdMapping idmap = {
251                 .input_base = min_bus << 8,
252                 .id_count = (max_bus - min_bus + 1) << 8,
253             };
254             g_array_append_val(idmap_blob, idmap);
255         }
256     }
257 
258     return 0;
259 }
260 
261 static int iort_idmap_compare(gconstpointer a, gconstpointer b)
262 {
263     AcpiIortIdMapping *idmap_a = (AcpiIortIdMapping *)a;
264     AcpiIortIdMapping *idmap_b = (AcpiIortIdMapping *)b;
265 
266     return idmap_a->input_base - idmap_b->input_base;
267 }
268 
269 /* Compute ID ranges (RIDs) from RC that are directed to the ITS Group node */
270 static void create_rc_its_idmaps(GArray *its_idmaps, GArray *smmu_idmaps)
271 {
272     AcpiIortIdMapping *idmap;
273     AcpiIortIdMapping next_range = {0};
274 
275     /*
276      * Based on the RID ranges that are directed to the SMMU, determine the
277      * bypassed RID ranges, i.e., the ones that are directed to the ITS Group
278      * node and do not pass through the SMMU, by subtracting the SMMU-bound
279      * ranges from the full RID range (0x0000–0xFFFF).
280      */
281      for (int i = 0; i < smmu_idmaps->len; i++) {
282         idmap = &g_array_index(smmu_idmaps, AcpiIortIdMapping, i);
283 
284         if (next_range.input_base < idmap->input_base) {
285             next_range.id_count = idmap->input_base - next_range.input_base;
286             g_array_append_val(its_idmaps, next_range);
287         }
288 
289         next_range.input_base = idmap->input_base + idmap->id_count;
290     }
291 
292     /*
293      * Append the last RC -> ITS ID mapping.
294      *
295      * RIDs are 16-bit, according to the PCI Express 2.0 Base Specification, rev
296      * 0.9, section 2.2.6.2, "Transaction Descriptor - Transaction ID Field",
297      * hence the end of the range is 0x10000.
298      */
299     if (next_range.input_base < 0x10000) {
300         next_range.id_count = 0x10000 - next_range.input_base;
301         g_array_append_val(its_idmaps, next_range);
302     }
303 }
304 
305 
306 /*
307  * Input Output Remapping Table (IORT)
308  * Conforms to "IO Remapping Table System Software on ARM Platforms",
309  * Document number: ARM DEN 0049E.b, Feb 2021
310  */
311 static void
312 build_iort(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
313 {
314     int i, nb_nodes, rc_mapping_count;
315     size_t node_size, smmu_offset = 0;
316     uint32_t id = 0;
317     GArray *rc_smmu_idmaps = g_array_new(false, true, sizeof(AcpiIortIdMapping));
318     GArray *rc_its_idmaps = g_array_new(false, true, sizeof(AcpiIortIdMapping));
319 
320     AcpiTable table = { .sig = "IORT", .rev = 3, .oem_id = vms->oem_id,
321                         .oem_table_id = vms->oem_table_id };
322     /* Table 2 The IORT */
323     acpi_table_begin(&table, table_data);
324 
325     if (vms->iommu == VIRT_IOMMU_SMMUV3) {
326         object_child_foreach_recursive(object_get_root(),
327                                        iort_host_bridges, rc_smmu_idmaps);
328 
329         /* Sort the smmu idmap by input_base */
330         g_array_sort(rc_smmu_idmaps, iort_idmap_compare);
331 
332         /*
333          * Knowing the ID ranges from the RC to the SMMU, it's possible to
334          * determine the ID ranges from RC that are directed to the ITS.
335          */
336         create_rc_its_idmaps(rc_its_idmaps, rc_smmu_idmaps);
337 
338         nb_nodes = 2; /* RC and SMMUv3 */
339         rc_mapping_count = rc_smmu_idmaps->len;
340 
341         if (vms->its) {
342             /*
343              * Knowing the ID ranges from the RC to the SMMU, it's possible to
344              * determine the ID ranges from RC that go directly to ITS.
345              */
346             create_rc_its_idmaps(rc_its_idmaps, rc_smmu_idmaps);
347 
348             nb_nodes++; /* ITS */
349             rc_mapping_count += rc_its_idmaps->len;
350         }
351     } else {
352         if (vms->its) {
353             nb_nodes = 2; /* RC and ITS */
354             rc_mapping_count = 1; /* Direct map to ITS */
355         } else {
356             nb_nodes = 1; /* RC only */
357             rc_mapping_count = 0; /* No output mapping */
358         }
359     }
360     /* Number of IORT Nodes */
361     build_append_int_noprefix(table_data, nb_nodes, 4);
362 
363     /* Offset to Array of IORT Nodes */
364     build_append_int_noprefix(table_data, IORT_NODE_OFFSET, 4);
365     build_append_int_noprefix(table_data, 0, 4); /* Reserved */
366 
367     if (vms->its) {
368         /* Table 12 ITS Group Format */
369         build_append_int_noprefix(table_data, 0 /* ITS Group */, 1); /* Type */
370         node_size =  20 /* fixed header size */ + 4 /* 1 GIC ITS Identifier */;
371         build_append_int_noprefix(table_data, node_size, 2); /* Length */
372         build_append_int_noprefix(table_data, 1, 1); /* Revision */
373         build_append_int_noprefix(table_data, id++, 4); /* Identifier */
374         build_append_int_noprefix(table_data, 0, 4); /* Number of ID mappings */
375         build_append_int_noprefix(table_data, 0, 4); /* Reference to ID Array */
376         build_append_int_noprefix(table_data, 1, 4); /* Number of ITSs */
377         /* GIC ITS Identifier Array */
378         build_append_int_noprefix(table_data, 0 /* MADT translation_id */, 4);
379     }
380 
381     if (vms->iommu == VIRT_IOMMU_SMMUV3) {
382         int irq =  vms->irqmap[VIRT_SMMU] + ARM_SPI_BASE;
383         int smmu_mapping_count, offset_to_id_array;
384 
385         if (vms->its) {
386             smmu_mapping_count = 1; /* ITS Group node */
387             offset_to_id_array = SMMU_V3_ENTRY_SIZE; /* Just after the header */
388         } else {
389             smmu_mapping_count = 0; /* No ID mappings */
390             offset_to_id_array = 0; /* No ID mappings array */
391         }
392         smmu_offset = table_data->len - table.table_offset;
393         /* Table 9 SMMUv3 Format */
394         build_append_int_noprefix(table_data, 4 /* SMMUv3 */, 1); /* Type */
395         node_size =  SMMU_V3_ENTRY_SIZE +
396                      (ID_MAPPING_ENTRY_SIZE * smmu_mapping_count);
397         build_append_int_noprefix(table_data, node_size, 2); /* Length */
398         build_append_int_noprefix(table_data, 4, 1); /* Revision */
399         build_append_int_noprefix(table_data, id++, 4); /* Identifier */
400         /* Number of ID mappings */
401         build_append_int_noprefix(table_data, smmu_mapping_count, 4);
402         /* Reference to ID Array */
403         build_append_int_noprefix(table_data, offset_to_id_array, 4);
404         /* Base address */
405         build_append_int_noprefix(table_data, vms->memmap[VIRT_SMMU].base, 8);
406         /* Flags */
407         build_append_int_noprefix(table_data, 1 /* COHACC Override */, 4);
408         build_append_int_noprefix(table_data, 0, 4); /* Reserved */
409         build_append_int_noprefix(table_data, 0, 8); /* VATOS address */
410         /* Model */
411         build_append_int_noprefix(table_data, 0 /* Generic SMMU-v3 */, 4);
412         build_append_int_noprefix(table_data, irq, 4); /* Event */
413         build_append_int_noprefix(table_data, irq + 1, 4); /* PRI */
414         build_append_int_noprefix(table_data, irq + 3, 4); /* GERR */
415         build_append_int_noprefix(table_data, irq + 2, 4); /* Sync */
416         build_append_int_noprefix(table_data, 0, 4); /* Proximity domain */
417         /* DeviceID mapping index (ignored since interrupts are GSIV based) */
418         build_append_int_noprefix(table_data, 0, 4);
419         /* Array of ID mappings */
420         if (smmu_mapping_count) {
421             /* Output IORT node is the ITS Group node (the first node). */
422             build_iort_id_mapping(table_data, 0, 0x10000, IORT_NODE_OFFSET);
423         }
424     }
425 
426     /* Table 17 Root Complex Node */
427     build_append_int_noprefix(table_data, 2 /* Root complex */, 1); /* Type */
428     node_size =  ROOT_COMPLEX_ENTRY_SIZE +
429                  ID_MAPPING_ENTRY_SIZE * rc_mapping_count;
430     build_append_int_noprefix(table_data, node_size, 2); /* Length */
431     build_append_int_noprefix(table_data, 3, 1); /* Revision */
432     build_append_int_noprefix(table_data, id++, 4); /* Identifier */
433     /* Number of ID mappings */
434     build_append_int_noprefix(table_data, rc_mapping_count, 4);
435     /* Reference to ID Array */
436     build_append_int_noprefix(table_data, ROOT_COMPLEX_ENTRY_SIZE, 4);
437 
438     /* Table 14 Memory access properties */
439     /* CCA: Cache Coherent Attribute */
440     build_append_int_noprefix(table_data, 1 /* fully coherent */, 4);
441     build_append_int_noprefix(table_data, 0, 1); /* AH: Note Allocation Hints */
442     build_append_int_noprefix(table_data, 0, 2); /* Reserved */
443     /* Table 15 Memory Access Flags */
444     build_append_int_noprefix(table_data, 0x3 /* CCA = CPM = DACS = 1 */, 1);
445 
446     build_append_int_noprefix(table_data, 0, 4); /* ATS Attribute */
447     /* MCFG pci_segment */
448     build_append_int_noprefix(table_data, 0, 4); /* PCI Segment number */
449 
450     /* Memory address size limit */
451     build_append_int_noprefix(table_data, 64, 1);
452 
453     build_append_int_noprefix(table_data, 0, 3); /* Reserved */
454 
455     /* Output Reference */
456     if (vms->iommu == VIRT_IOMMU_SMMUV3) {
457         AcpiIortIdMapping *range;
458 
459         /*
460          * Map RIDs (input) from RC to SMMUv3 nodes: RC -> SMMUv3.
461          *
462          * N.B.: The mapping from SMMUv3 to ITS Group node (SMMUv3 -> ITS) is
463          * defined in the SMMUv3 table, where all SMMUv3 IDs are mapped to the
464          * ITS Group node, if ITS is available.
465          */
466         for (i = 0; i < rc_smmu_idmaps->len; i++) {
467             range = &g_array_index(rc_smmu_idmaps, AcpiIortIdMapping, i);
468             /* Output IORT node is the SMMUv3 node. */
469             build_iort_id_mapping(table_data, range->input_base,
470                                   range->id_count, smmu_offset);
471         }
472 
473         if (vms->its) {
474             /*
475              * Map bypassed (don't go through the SMMU) RIDs (input) to
476              * ITS Group node directly: RC -> ITS.
477              */
478             for (i = 0; i < rc_its_idmaps->len; i++) {
479                 range = &g_array_index(rc_its_idmaps, AcpiIortIdMapping, i);
480                 /* Output IORT node is the ITS Group node (the first node). */
481                 build_iort_id_mapping(table_data, range->input_base,
482                                       range->id_count, IORT_NODE_OFFSET);
483             }
484         }
485     } else {
486         /*
487          * Map all RIDs (input) to ITS Group node directly, since there is no
488          * SMMU: RC -> ITS.
489          * Output IORT node is the ITS Group node (the first node).
490          */
491         build_iort_id_mapping(table_data, 0, 0x10000, IORT_NODE_OFFSET);
492     }
493 
494     acpi_table_end(linker, &table);
495     g_array_free(rc_smmu_idmaps, true);
496     g_array_free(rc_its_idmaps, true);
497 }
498 
499 /*
500  * Serial Port Console Redirection Table (SPCR)
501  * Rev: 1.07
502  */
503 static void
504 spcr_setup(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
505 {
506     AcpiSpcrData serial = {
507         .interface_type = 3,       /* ARM PL011 UART */
508         .base_addr.id = AML_AS_SYSTEM_MEMORY,
509         .base_addr.width = 32,
510         .base_addr.offset = 0,
511         .base_addr.size = 3,
512         .base_addr.addr = vms->memmap[VIRT_UART0].base,
513         .interrupt_type = (1 << 3),/* Bit[3] ARMH GIC interrupt*/
514         .pc_interrupt = 0,         /* IRQ */
515         .interrupt = (vms->irqmap[VIRT_UART0] + ARM_SPI_BASE),
516         .baud_rate = 3,            /* 9600 */
517         .parity = 0,               /* No Parity */
518         .stop_bits = 1,            /* 1 Stop bit */
519         .flow_control = 1 << 1,    /* RTS/CTS hardware flow control */
520         .terminal_type = 0,        /* VT100 */
521         .language = 0,             /* Language */
522         .pci_device_id = 0xffff,   /* not a PCI device*/
523         .pci_vendor_id = 0xffff,   /* not a PCI device*/
524         .pci_bus = 0,
525         .pci_device = 0,
526         .pci_function = 0,
527         .pci_flags = 0,
528         .pci_segment = 0,
529     };
530     /*
531      * Passing NULL as the SPCR Table for Revision 2 doesn't support
532      * NameSpaceString.
533      */
534     build_spcr(table_data, linker, &serial, 2, vms->oem_id, vms->oem_table_id,
535                NULL);
536 }
537 
538 /*
539  * ACPI spec, Revision 5.1
540  * 5.2.16 System Resource Affinity Table (SRAT)
541  */
542 static void
543 build_srat(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
544 {
545     int i;
546     uint64_t mem_base;
547     MachineClass *mc = MACHINE_GET_CLASS(vms);
548     MachineState *ms = MACHINE(vms);
549     const CPUArchIdList *cpu_list = mc->possible_cpu_arch_ids(ms);
550     AcpiTable table = { .sig = "SRAT", .rev = 3, .oem_id = vms->oem_id,
551                         .oem_table_id = vms->oem_table_id };
552 
553     acpi_table_begin(&table, table_data);
554     build_append_int_noprefix(table_data, 1, 4); /* Reserved */
555     build_append_int_noprefix(table_data, 0, 8); /* Reserved */
556 
557     for (i = 0; i < cpu_list->len; ++i) {
558         uint32_t nodeid = cpu_list->cpus[i].props.node_id;
559         /*
560          * 5.2.16.4 GICC Affinity Structure
561          */
562         build_append_int_noprefix(table_data, 3, 1);      /* Type */
563         build_append_int_noprefix(table_data, 18, 1);     /* Length */
564         build_append_int_noprefix(table_data, nodeid, 4); /* Proximity Domain */
565         build_append_int_noprefix(table_data, i, 4); /* ACPI Processor UID */
566         /* Flags, Table 5-76 */
567         build_append_int_noprefix(table_data, 1 /* Enabled */, 4);
568         build_append_int_noprefix(table_data, 0, 4); /* Clock Domain */
569     }
570 
571     mem_base = vms->memmap[VIRT_MEM].base;
572     for (i = 0; i < ms->numa_state->num_nodes; ++i) {
573         if (ms->numa_state->nodes[i].node_mem > 0) {
574             build_srat_memory(table_data, mem_base,
575                               ms->numa_state->nodes[i].node_mem, i,
576                               MEM_AFFINITY_ENABLED);
577             mem_base += ms->numa_state->nodes[i].node_mem;
578         }
579     }
580 
581     build_srat_generic_affinity_structures(table_data);
582 
583     if (ms->nvdimms_state->is_enabled) {
584         nvdimm_build_srat(table_data);
585     }
586 
587     if (ms->device_memory) {
588         build_srat_memory(table_data, ms->device_memory->base,
589                           memory_region_size(&ms->device_memory->mr),
590                           ms->numa_state->num_nodes - 1,
591                           MEM_AFFINITY_HOTPLUGGABLE | MEM_AFFINITY_ENABLED);
592     }
593 
594     acpi_table_end(linker, &table);
595 }
596 
597 /*
598  * ACPI spec, Revision 6.5
599  * 5.2.25 Generic Timer Description Table (GTDT)
600  */
601 static void
602 build_gtdt(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
603 {
604     /*
605      * Table 5-117 Flag Definitions
606      * set only "Timer interrupt Mode" and assume "Timer Interrupt
607      * polarity" bit as '0: Interrupt is Active high'
608      */
609     const uint32_t irqflags = 0;  /* Interrupt is Level triggered  */
610     AcpiTable table = { .sig = "GTDT", .rev = 3, .oem_id = vms->oem_id,
611                         .oem_table_id = vms->oem_table_id };
612 
613     acpi_table_begin(&table, table_data);
614 
615     /* CntControlBase Physical Address */
616     build_append_int_noprefix(table_data, 0xFFFFFFFFFFFFFFFF, 8);
617     build_append_int_noprefix(table_data, 0, 4); /* Reserved */
618     /*
619      * FIXME: clarify comment:
620      * The interrupt values are the same with the device tree when adding 16
621      */
622     /* Secure EL1 timer GSIV */
623     build_append_int_noprefix(table_data, ARCH_TIMER_S_EL1_IRQ, 4);
624     /* Secure EL1 timer Flags */
625     build_append_int_noprefix(table_data, irqflags, 4);
626     /* Non-Secure EL1 timer GSIV */
627     build_append_int_noprefix(table_data, ARCH_TIMER_NS_EL1_IRQ, 4);
628     /* Non-Secure EL1 timer Flags */
629     build_append_int_noprefix(table_data, irqflags |
630                               1UL << 2, /* Always-on Capability */
631                               4);
632     /* Virtual timer GSIV */
633     build_append_int_noprefix(table_data, ARCH_TIMER_VIRT_IRQ, 4);
634     /* Virtual Timer Flags */
635     build_append_int_noprefix(table_data, irqflags, 4);
636     /* Non-Secure EL2 timer GSIV */
637     build_append_int_noprefix(table_data, ARCH_TIMER_NS_EL2_IRQ, 4);
638     /* Non-Secure EL2 timer Flags */
639     build_append_int_noprefix(table_data, irqflags, 4);
640     /* CntReadBase Physical address */
641     build_append_int_noprefix(table_data, 0xFFFFFFFFFFFFFFFF, 8);
642     /* Platform Timer Count */
643     build_append_int_noprefix(table_data, 0, 4);
644     /* Platform Timer Offset */
645     build_append_int_noprefix(table_data, 0, 4);
646     if (vms->ns_el2_virt_timer_irq) {
647         /* Virtual EL2 Timer GSIV */
648         build_append_int_noprefix(table_data, ARCH_TIMER_NS_EL2_VIRT_IRQ, 4);
649         /* Virtual EL2 Timer Flags */
650         build_append_int_noprefix(table_data, irqflags, 4);
651     } else {
652         build_append_int_noprefix(table_data, 0, 4);
653         build_append_int_noprefix(table_data, 0, 4);
654     }
655     acpi_table_end(linker, &table);
656 }
657 
658 /* Debug Port Table 2 (DBG2) */
659 static void
660 build_dbg2(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
661 {
662     AcpiTable table = { .sig = "DBG2", .rev = 0, .oem_id = vms->oem_id,
663                         .oem_table_id = vms->oem_table_id };
664     int dbg2devicelength;
665     const char name[] = "COM0";
666     const int namespace_length = sizeof(name);
667 
668     acpi_table_begin(&table, table_data);
669 
670     dbg2devicelength = 22 + /* BaseAddressRegister[] offset */
671                        12 + /* BaseAddressRegister[] */
672                        4 + /* AddressSize[] */
673                        namespace_length /* NamespaceString[] */;
674 
675     /* OffsetDbgDeviceInfo */
676     build_append_int_noprefix(table_data, 44, 4);
677     /* NumberDbgDeviceInfo */
678     build_append_int_noprefix(table_data, 1, 4);
679 
680     /* Table 2. Debug Device Information structure format */
681     build_append_int_noprefix(table_data, 0, 1); /* Revision */
682     build_append_int_noprefix(table_data, dbg2devicelength, 2); /* Length */
683     /* NumberofGenericAddressRegisters */
684     build_append_int_noprefix(table_data, 1, 1);
685     /* NameSpaceStringLength */
686     build_append_int_noprefix(table_data, namespace_length, 2);
687     build_append_int_noprefix(table_data, 38, 2); /* NameSpaceStringOffset */
688     build_append_int_noprefix(table_data, 0, 2); /* OemDataLength */
689     /* OemDataOffset (0 means no OEM data) */
690     build_append_int_noprefix(table_data, 0, 2);
691 
692     /* Port Type */
693     build_append_int_noprefix(table_data, 0x8000 /* Serial */, 2);
694     /* Port Subtype */
695     build_append_int_noprefix(table_data, 0x3 /* ARM PL011 UART */, 2);
696     build_append_int_noprefix(table_data, 0, 2); /* Reserved */
697     /* BaseAddressRegisterOffset */
698     build_append_int_noprefix(table_data, 22, 2);
699     /* AddressSizeOffset */
700     build_append_int_noprefix(table_data, 34, 2);
701 
702     /* BaseAddressRegister[] */
703     build_append_gas(table_data, AML_AS_SYSTEM_MEMORY, 32, 0, 3,
704                      vms->memmap[VIRT_UART0].base);
705 
706     /* AddressSize[] */
707     build_append_int_noprefix(table_data,
708                               vms->memmap[VIRT_UART0].size, 4);
709 
710     /* NamespaceString[] */
711     g_array_append_vals(table_data, name, namespace_length);
712 
713     acpi_table_end(linker, &table);
714 };
715 
716 /*
717  * ACPI spec, Revision 6.0 Errata A
718  * 5.2.12 Multiple APIC Description Table (MADT)
719  */
720 static void build_append_gicr(GArray *table_data, uint64_t base, uint32_t size)
721 {
722     build_append_int_noprefix(table_data, 0xE, 1);  /* Type */
723     build_append_int_noprefix(table_data, 16, 1);   /* Length */
724     build_append_int_noprefix(table_data, 0, 2);    /* Reserved */
725     /* Discovery Range Base Address */
726     build_append_int_noprefix(table_data, base, 8);
727     build_append_int_noprefix(table_data, size, 4); /* Discovery Range Length */
728 }
729 
730 static void
731 build_madt(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
732 {
733     int i;
734     const MemMapEntry *memmap = vms->memmap;
735     AcpiTable table = { .sig = "APIC", .rev = 4, .oem_id = vms->oem_id,
736                         .oem_table_id = vms->oem_table_id };
737 
738     acpi_table_begin(&table, table_data);
739     /* Local Interrupt Controller Address */
740     build_append_int_noprefix(table_data, 0, 4);
741     build_append_int_noprefix(table_data, 0, 4);   /* Flags */
742 
743     /* 5.2.12.15 GIC Distributor Structure */
744     build_append_int_noprefix(table_data, 0xC, 1); /* Type */
745     build_append_int_noprefix(table_data, 24, 1);  /* Length */
746     build_append_int_noprefix(table_data, 0, 2);   /* Reserved */
747     build_append_int_noprefix(table_data, 0, 4);   /* GIC ID */
748     /* Physical Base Address */
749     build_append_int_noprefix(table_data, memmap[VIRT_GIC_DIST].base, 8);
750     build_append_int_noprefix(table_data, 0, 4);   /* System Vector Base */
751     /* GIC version */
752     build_append_int_noprefix(table_data, vms->gic_version, 1);
753     build_append_int_noprefix(table_data, 0, 3);   /* Reserved */
754 
755     for (i = 0; i < MACHINE(vms)->smp.cpus; i++) {
756         ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(i));
757         uint64_t physical_base_address = 0, gich = 0, gicv = 0;
758         uint32_t vgic_interrupt = vms->virt ? ARCH_GIC_MAINT_IRQ : 0;
759         uint32_t pmu_interrupt = arm_feature(&armcpu->env, ARM_FEATURE_PMU) ?
760                                              VIRTUAL_PMU_IRQ : 0;
761 
762         if (vms->gic_version == VIRT_GIC_VERSION_2) {
763             physical_base_address = memmap[VIRT_GIC_CPU].base;
764             gicv = memmap[VIRT_GIC_VCPU].base;
765             gich = memmap[VIRT_GIC_HYP].base;
766         }
767 
768         /* 5.2.12.14 GIC Structure */
769         build_append_int_noprefix(table_data, 0xB, 1);  /* Type */
770         build_append_int_noprefix(table_data, 80, 1);   /* Length */
771         build_append_int_noprefix(table_data, 0, 2);    /* Reserved */
772         build_append_int_noprefix(table_data, i, 4);    /* GIC ID */
773         build_append_int_noprefix(table_data, i, 4);    /* ACPI Processor UID */
774         /* Flags */
775         build_append_int_noprefix(table_data, 1, 4);    /* Enabled */
776         /* Parking Protocol Version */
777         build_append_int_noprefix(table_data, 0, 4);
778         /* Performance Interrupt GSIV */
779         build_append_int_noprefix(table_data, pmu_interrupt, 4);
780         build_append_int_noprefix(table_data, 0, 8); /* Parked Address */
781         /* Physical Base Address */
782         build_append_int_noprefix(table_data, physical_base_address, 8);
783         build_append_int_noprefix(table_data, gicv, 8); /* GICV */
784         build_append_int_noprefix(table_data, gich, 8); /* GICH */
785         /* VGIC Maintenance interrupt */
786         build_append_int_noprefix(table_data, vgic_interrupt, 4);
787         build_append_int_noprefix(table_data, 0, 8);    /* GICR Base Address*/
788         /* MPIDR */
789         build_append_int_noprefix(table_data, arm_cpu_mp_affinity(armcpu), 8);
790         /* Processor Power Efficiency Class */
791         build_append_int_noprefix(table_data, 0, 1);
792         /* Reserved */
793         build_append_int_noprefix(table_data, 0, 3);
794     }
795 
796     if (vms->gic_version != VIRT_GIC_VERSION_2) {
797         build_append_gicr(table_data, memmap[VIRT_GIC_REDIST].base,
798                                       memmap[VIRT_GIC_REDIST].size);
799         if (virt_gicv3_redist_region_count(vms) == 2) {
800             build_append_gicr(table_data, memmap[VIRT_HIGH_GIC_REDIST2].base,
801                                           memmap[VIRT_HIGH_GIC_REDIST2].size);
802         }
803 
804         if (vms->its) {
805             /*
806              * ACPI spec, Revision 6.0 Errata A
807              * (original 6.0 definition has invalid Length)
808              * 5.2.12.18 GIC ITS Structure
809              */
810             build_append_int_noprefix(table_data, 0xF, 1);  /* Type */
811             build_append_int_noprefix(table_data, 20, 1);   /* Length */
812             build_append_int_noprefix(table_data, 0, 2);    /* Reserved */
813             build_append_int_noprefix(table_data, 0, 4);    /* GIC ITS ID */
814             /* Physical Base Address */
815             build_append_int_noprefix(table_data, memmap[VIRT_GIC_ITS].base, 8);
816             build_append_int_noprefix(table_data, 0, 4);    /* Reserved */
817         }
818     } else {
819         const uint16_t spi_base = vms->irqmap[VIRT_GIC_V2M] + ARM_SPI_BASE;
820 
821         /* 5.2.12.16 GIC MSI Frame Structure */
822         build_append_int_noprefix(table_data, 0xD, 1);  /* Type */
823         build_append_int_noprefix(table_data, 24, 1);   /* Length */
824         build_append_int_noprefix(table_data, 0, 2);    /* Reserved */
825         build_append_int_noprefix(table_data, 0, 4);    /* GIC MSI Frame ID */
826         /* Physical Base Address */
827         build_append_int_noprefix(table_data, memmap[VIRT_GIC_V2M].base, 8);
828         build_append_int_noprefix(table_data, 1, 4);    /* Flags */
829         /* SPI Count */
830         build_append_int_noprefix(table_data, NUM_GICV2M_SPIS, 2);
831         build_append_int_noprefix(table_data, spi_base, 2); /* SPI Base */
832     }
833     acpi_table_end(linker, &table);
834 }
835 
836 /* FADT */
837 static void build_fadt_rev6(GArray *table_data, BIOSLinker *linker,
838                             VirtMachineState *vms, unsigned dsdt_tbl_offset)
839 {
840     /* ACPI v6.3 */
841     AcpiFadtData fadt = {
842         .rev = 6,
843         .minor_ver = 3,
844         .flags = 1 << ACPI_FADT_F_HW_REDUCED_ACPI,
845         .xdsdt_tbl_offset = &dsdt_tbl_offset,
846     };
847 
848     switch (vms->psci_conduit) {
849     case QEMU_PSCI_CONDUIT_DISABLED:
850         fadt.arm_boot_arch = 0;
851         break;
852     case QEMU_PSCI_CONDUIT_HVC:
853         fadt.arm_boot_arch = ACPI_FADT_ARM_PSCI_COMPLIANT |
854                              ACPI_FADT_ARM_PSCI_USE_HVC;
855         break;
856     case QEMU_PSCI_CONDUIT_SMC:
857         fadt.arm_boot_arch = ACPI_FADT_ARM_PSCI_COMPLIANT;
858         break;
859     default:
860         g_assert_not_reached();
861     }
862 
863     build_fadt(table_data, linker, &fadt, vms->oem_id, vms->oem_table_id);
864 }
865 
866 /* DSDT */
867 static void
868 build_dsdt(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
869 {
870     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
871     Aml *scope, *dsdt;
872     MachineState *ms = MACHINE(vms);
873     const MemMapEntry *memmap = vms->memmap;
874     const int *irqmap = vms->irqmap;
875     AcpiTable table = { .sig = "DSDT", .rev = 2, .oem_id = vms->oem_id,
876                         .oem_table_id = vms->oem_table_id };
877 
878     acpi_table_begin(&table, table_data);
879     dsdt = init_aml_allocator();
880 
881     /* When booting the VM with UEFI, UEFI takes ownership of the RTC hardware.
882      * While UEFI can use libfdt to disable the RTC device node in the DTB that
883      * it passes to the OS, it cannot modify AML. Therefore, we won't generate
884      * the RTC ACPI device at all when using UEFI.
885      */
886     scope = aml_scope("\\_SB");
887     acpi_dsdt_add_cpus(scope, vms);
888     acpi_dsdt_add_uart(scope, &memmap[VIRT_UART0],
889                        (irqmap[VIRT_UART0] + ARM_SPI_BASE), 0);
890     if (vms->second_ns_uart_present) {
891         acpi_dsdt_add_uart(scope, &memmap[VIRT_UART1],
892                            (irqmap[VIRT_UART1] + ARM_SPI_BASE), 1);
893     }
894     if (vmc->acpi_expose_flash) {
895         acpi_dsdt_add_flash(scope, &memmap[VIRT_FLASH]);
896     }
897     fw_cfg_acpi_dsdt_add(scope, &memmap[VIRT_FW_CFG]);
898     virtio_acpi_dsdt_add(scope, memmap[VIRT_MMIO].base, memmap[VIRT_MMIO].size,
899                          (irqmap[VIRT_MMIO] + ARM_SPI_BASE),
900                          0, NUM_VIRTIO_TRANSPORTS);
901     acpi_dsdt_add_pci(scope, memmap, irqmap[VIRT_PCIE] + ARM_SPI_BASE, vms);
902     if (vms->acpi_dev) {
903         build_ged_aml(scope, "\\_SB."GED_DEVICE,
904                       HOTPLUG_HANDLER(vms->acpi_dev),
905                       irqmap[VIRT_ACPI_GED] + ARM_SPI_BASE, AML_SYSTEM_MEMORY,
906                       memmap[VIRT_ACPI_GED].base);
907     } else {
908         acpi_dsdt_add_gpio(scope, &memmap[VIRT_GPIO],
909                            (irqmap[VIRT_GPIO] + ARM_SPI_BASE));
910     }
911 
912     if (vms->acpi_dev) {
913         uint32_t event = object_property_get_uint(OBJECT(vms->acpi_dev),
914                                                   "ged-event", &error_abort);
915 
916         if (event & ACPI_GED_MEM_HOTPLUG_EVT) {
917             build_memory_hotplug_aml(scope, ms->ram_slots, "\\_SB", NULL,
918                                      AML_SYSTEM_MEMORY,
919                                      memmap[VIRT_PCDIMM_ACPI].base);
920         }
921     }
922 
923     acpi_dsdt_add_power_button(scope);
924 #ifdef CONFIG_TPM
925     acpi_dsdt_add_tpm(scope, vms);
926 #endif
927 
928     aml_append(dsdt, scope);
929 
930     /* copy AML table into ACPI tables blob */
931     g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);
932 
933     acpi_table_end(linker, &table);
934     free_aml_allocator();
935 }
936 
937 typedef
938 struct AcpiBuildState {
939     /* Copy of table in RAM (for patching). */
940     MemoryRegion *table_mr;
941     MemoryRegion *rsdp_mr;
942     MemoryRegion *linker_mr;
943     /* Is table patched? */
944     bool patched;
945 } AcpiBuildState;
946 
947 static void acpi_align_size(GArray *blob, unsigned align)
948 {
949     /*
950      * Align size to multiple of given size. This reduces the chance
951      * we need to change size in the future (breaking cross version migration).
952      */
953     g_array_set_size(blob, ROUND_UP(acpi_data_len(blob), align));
954 }
955 
956 static
957 void virt_acpi_build(VirtMachineState *vms, AcpiBuildTables *tables)
958 {
959     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
960     GArray *table_offsets;
961     unsigned dsdt, xsdt;
962     GArray *tables_blob = tables->table_data;
963     MachineState *ms = MACHINE(vms);
964 
965     table_offsets = g_array_new(false, true /* clear */,
966                                         sizeof(uint32_t));
967 
968     bios_linker_loader_alloc(tables->linker,
969                              ACPI_BUILD_TABLE_FILE, tables_blob,
970                              64, false /* high memory */);
971 
972     /* DSDT is pointed to by FADT */
973     dsdt = tables_blob->len;
974     build_dsdt(tables_blob, tables->linker, vms);
975 
976     /* FADT MADT PPTT GTDT MCFG SPCR DBG2 pointed to by RSDT */
977     acpi_add_table(table_offsets, tables_blob);
978     build_fadt_rev6(tables_blob, tables->linker, vms, dsdt);
979 
980     acpi_add_table(table_offsets, tables_blob);
981     build_madt(tables_blob, tables->linker, vms);
982 
983     if (!vmc->no_cpu_topology) {
984         acpi_add_table(table_offsets, tables_blob);
985         build_pptt(tables_blob, tables->linker, ms,
986                    vms->oem_id, vms->oem_table_id);
987     }
988 
989     acpi_add_table(table_offsets, tables_blob);
990     build_gtdt(tables_blob, tables->linker, vms);
991 
992     acpi_add_table(table_offsets, tables_blob);
993     {
994         AcpiMcfgInfo mcfg = {
995            .base = vms->memmap[VIRT_ECAM_ID(vms->highmem_ecam)].base,
996            .size = vms->memmap[VIRT_ECAM_ID(vms->highmem_ecam)].size,
997         };
998         build_mcfg(tables_blob, tables->linker, &mcfg, vms->oem_id,
999                    vms->oem_table_id);
1000     }
1001 
1002     acpi_add_table(table_offsets, tables_blob);
1003     spcr_setup(tables_blob, tables->linker, vms);
1004 
1005     acpi_add_table(table_offsets, tables_blob);
1006     build_dbg2(tables_blob, tables->linker, vms);
1007 
1008     if (vms->ras) {
1009         acpi_add_table(table_offsets, tables_blob);
1010         acpi_build_hest(tables_blob, tables->hardware_errors, tables->linker,
1011                         vms->oem_id, vms->oem_table_id);
1012     }
1013 
1014     if (ms->numa_state->num_nodes > 0) {
1015         acpi_add_table(table_offsets, tables_blob);
1016         build_srat(tables_blob, tables->linker, vms);
1017         if (ms->numa_state->have_numa_distance) {
1018             acpi_add_table(table_offsets, tables_blob);
1019             build_slit(tables_blob, tables->linker, ms, vms->oem_id,
1020                        vms->oem_table_id);
1021         }
1022 
1023         if (ms->numa_state->hmat_enabled) {
1024             acpi_add_table(table_offsets, tables_blob);
1025             build_hmat(tables_blob, tables->linker, ms->numa_state,
1026                        vms->oem_id, vms->oem_table_id);
1027         }
1028     }
1029 
1030     if (ms->nvdimms_state->is_enabled) {
1031         nvdimm_build_acpi(table_offsets, tables_blob, tables->linker,
1032                           ms->nvdimms_state, ms->ram_slots, vms->oem_id,
1033                           vms->oem_table_id);
1034     }
1035 
1036     acpi_add_table(table_offsets, tables_blob);
1037     build_iort(tables_blob, tables->linker, vms);
1038 
1039 #ifdef CONFIG_TPM
1040     if (tpm_get_version(tpm_find()) == TPM_VERSION_2_0) {
1041         acpi_add_table(table_offsets, tables_blob);
1042         build_tpm2(tables_blob, tables->linker, tables->tcpalog, vms->oem_id,
1043                    vms->oem_table_id);
1044     }
1045 #endif
1046 
1047     if (vms->iommu == VIRT_IOMMU_VIRTIO) {
1048         acpi_add_table(table_offsets, tables_blob);
1049         build_viot(ms, tables_blob, tables->linker, vms->virtio_iommu_bdf,
1050                    vms->oem_id, vms->oem_table_id);
1051     }
1052 
1053     /* XSDT is pointed to by RSDP */
1054     xsdt = tables_blob->len;
1055     build_xsdt(tables_blob, tables->linker, table_offsets, vms->oem_id,
1056                vms->oem_table_id);
1057 
1058     /* RSDP is in FSEG memory, so allocate it separately */
1059     {
1060         AcpiRsdpData rsdp_data = {
1061             .revision = 2,
1062             .oem_id = vms->oem_id,
1063             .xsdt_tbl_offset = &xsdt,
1064             .rsdt_tbl_offset = NULL,
1065         };
1066         build_rsdp(tables->rsdp, tables->linker, &rsdp_data);
1067     }
1068 
1069     /*
1070      * The align size is 128, warn if 64k is not enough therefore
1071      * the align size could be resized.
1072      */
1073     if (tables_blob->len > ACPI_BUILD_TABLE_SIZE / 2) {
1074         warn_report("ACPI table size %u exceeds %d bytes,"
1075                     " migration may not work",
1076                     tables_blob->len, ACPI_BUILD_TABLE_SIZE / 2);
1077         error_printf("Try removing CPUs, NUMA nodes, memory slots"
1078                      " or PCI bridges.\n");
1079     }
1080     acpi_align_size(tables_blob, ACPI_BUILD_TABLE_SIZE);
1081 
1082 
1083     /* Cleanup memory that's no longer used. */
1084     g_array_free(table_offsets, true);
1085 }
1086 
1087 static void acpi_ram_update(MemoryRegion *mr, GArray *data)
1088 {
1089     uint32_t size = acpi_data_len(data);
1090 
1091     /* Make sure RAM size is correct - in case it got changed
1092      * e.g. by migration */
1093     memory_region_ram_resize(mr, size, &error_abort);
1094 
1095     memcpy(memory_region_get_ram_ptr(mr), data->data, size);
1096     memory_region_set_dirty(mr, 0, size);
1097 }
1098 
1099 static void virt_acpi_build_update(void *build_opaque)
1100 {
1101     AcpiBuildState *build_state = build_opaque;
1102     AcpiBuildTables tables;
1103 
1104     /* No state to update or already patched? Nothing to do. */
1105     if (!build_state || build_state->patched) {
1106         return;
1107     }
1108     build_state->patched = true;
1109 
1110     acpi_build_tables_init(&tables);
1111 
1112     virt_acpi_build(VIRT_MACHINE(qdev_get_machine()), &tables);
1113 
1114     acpi_ram_update(build_state->table_mr, tables.table_data);
1115     acpi_ram_update(build_state->rsdp_mr, tables.rsdp);
1116     acpi_ram_update(build_state->linker_mr, tables.linker->cmd_blob);
1117 
1118     acpi_build_tables_cleanup(&tables, true);
1119 }
1120 
1121 static void virt_acpi_build_reset(void *build_opaque)
1122 {
1123     AcpiBuildState *build_state = build_opaque;
1124     build_state->patched = false;
1125 }
1126 
1127 static const VMStateDescription vmstate_virt_acpi_build = {
1128     .name = "virt_acpi_build",
1129     .version_id = 1,
1130     .minimum_version_id = 1,
1131     .fields = (const VMStateField[]) {
1132         VMSTATE_BOOL(patched, AcpiBuildState),
1133         VMSTATE_END_OF_LIST()
1134     },
1135 };
1136 
1137 void virt_acpi_setup(VirtMachineState *vms)
1138 {
1139     AcpiBuildTables tables;
1140     AcpiBuildState *build_state;
1141     AcpiGedState *acpi_ged_state;
1142 
1143     if (!vms->fw_cfg) {
1144         trace_virt_acpi_setup();
1145         return;
1146     }
1147 
1148     if (!virt_is_acpi_enabled(vms)) {
1149         trace_virt_acpi_setup();
1150         return;
1151     }
1152 
1153     build_state = g_malloc0(sizeof *build_state);
1154 
1155     acpi_build_tables_init(&tables);
1156     virt_acpi_build(vms, &tables);
1157 
1158     /* Now expose it all to Guest */
1159     build_state->table_mr = acpi_add_rom_blob(virt_acpi_build_update,
1160                                               build_state, tables.table_data,
1161                                               ACPI_BUILD_TABLE_FILE);
1162     assert(build_state->table_mr != NULL);
1163 
1164     build_state->linker_mr = acpi_add_rom_blob(virt_acpi_build_update,
1165                                                build_state,
1166                                                tables.linker->cmd_blob,
1167                                                ACPI_BUILD_LOADER_FILE);
1168 
1169     fw_cfg_add_file(vms->fw_cfg, ACPI_BUILD_TPMLOG_FILE, tables.tcpalog->data,
1170                     acpi_data_len(tables.tcpalog));
1171 
1172     if (vms->ras) {
1173         assert(vms->acpi_dev);
1174         acpi_ged_state = ACPI_GED(vms->acpi_dev);
1175         acpi_ghes_add_fw_cfg(&acpi_ged_state->ghes_state,
1176                              vms->fw_cfg, tables.hardware_errors);
1177     }
1178 
1179     build_state->rsdp_mr = acpi_add_rom_blob(virt_acpi_build_update,
1180                                              build_state, tables.rsdp,
1181                                              ACPI_BUILD_RSDP_FILE);
1182 
1183     qemu_register_reset(virt_acpi_build_reset, build_state);
1184     virt_acpi_build_reset(build_state);
1185     vmstate_register(NULL, 0, &vmstate_virt_acpi_build, build_state);
1186 
1187     /* Cleanup tables but don't free the memory: we track it
1188      * in build_state.
1189      */
1190     acpi_build_tables_cleanup(&tables, false);
1191 }
1192