xref: /openbmc/qemu/hw/i386/acpi-build.c (revision c5539cb4269edf15d96bd0d75594757a80a39fa5)
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 "acpi-build.h"
24 #include <stddef.h>
25 #include <glib.h>
26 #include "qemu-common.h"
27 #include "qemu/bitmap.h"
28 #include "qemu/osdep.h"
29 #include "qemu/range.h"
30 #include "qemu/error-report.h"
31 #include "hw/pci/pci.h"
32 #include "qom/cpu.h"
33 #include "hw/i386/pc.h"
34 #include "target-i386/cpu.h"
35 #include "hw/timer/hpet.h"
36 #include "hw/i386/acpi-defs.h"
37 #include "hw/acpi/acpi.h"
38 #include "hw/nvram/fw_cfg.h"
39 #include "bios-linker-loader.h"
40 #include "hw/loader.h"
41 #include "hw/isa/isa.h"
42 #include "hw/acpi/memory_hotplug.h"
43 #include "sysemu/tpm.h"
44 #include "hw/acpi/tpm.h"
45 
46 /* Supported chipsets: */
47 #include "hw/acpi/piix4.h"
48 #include "hw/acpi/pcihp.h"
49 #include "hw/i386/ich9.h"
50 #include "hw/pci/pci_bus.h"
51 #include "hw/pci-host/q35.h"
52 
53 #include "hw/i386/q35-acpi-dsdt.hex"
54 #include "hw/i386/acpi-dsdt.hex"
55 
56 #include "qapi/qmp/qint.h"
57 #include "qom/qom-qobject.h"
58 
59 /* These are used to size the ACPI tables for -M pc-i440fx-1.7 and
60  * -M pc-i440fx-2.0.  Even if the actual amount of AML generated grows
61  * a little bit, there should be plenty of free space since the DSDT
62  * shrunk by ~1.5k between QEMU 2.0 and QEMU 2.1.
63  */
64 #define ACPI_BUILD_LEGACY_CPU_AML_SIZE    97
65 #define ACPI_BUILD_ALIGN_SIZE             0x1000
66 
67 #define ACPI_BUILD_TABLE_SIZE             0x20000
68 
69 typedef struct AcpiCpuInfo {
70     DECLARE_BITMAP(found_cpus, ACPI_CPU_HOTPLUG_ID_LIMIT);
71 } AcpiCpuInfo;
72 
73 typedef struct AcpiMcfgInfo {
74     uint64_t mcfg_base;
75     uint32_t mcfg_size;
76 } AcpiMcfgInfo;
77 
78 typedef struct AcpiPmInfo {
79     bool s3_disabled;
80     bool s4_disabled;
81     bool pcihp_bridge_en;
82     uint8_t s4_val;
83     uint16_t sci_int;
84     uint8_t acpi_enable_cmd;
85     uint8_t acpi_disable_cmd;
86     uint32_t gpe0_blk;
87     uint32_t gpe0_blk_len;
88     uint32_t io_base;
89 } AcpiPmInfo;
90 
91 typedef struct AcpiMiscInfo {
92     bool has_hpet;
93     bool has_tpm;
94     DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX);
95     const unsigned char *dsdt_code;
96     unsigned dsdt_size;
97     uint16_t pvpanic_port;
98 } AcpiMiscInfo;
99 
100 typedef struct AcpiBuildPciBusHotplugState {
101     GArray *device_table;
102     GArray *notify_table;
103     struct AcpiBuildPciBusHotplugState *parent;
104     bool pcihp_bridge_en;
105 } AcpiBuildPciBusHotplugState;
106 
107 static void acpi_get_dsdt(AcpiMiscInfo *info)
108 {
109     uint16_t *applesmc_sta;
110     Object *piix = piix4_pm_find();
111     Object *lpc = ich9_lpc_find();
112     assert(!!piix != !!lpc);
113 
114     if (piix) {
115         info->dsdt_code = AcpiDsdtAmlCode;
116         info->dsdt_size = sizeof AcpiDsdtAmlCode;
117         applesmc_sta = piix_dsdt_applesmc_sta;
118     }
119     if (lpc) {
120         info->dsdt_code = Q35AcpiDsdtAmlCode;
121         info->dsdt_size = sizeof Q35AcpiDsdtAmlCode;
122         applesmc_sta = q35_dsdt_applesmc_sta;
123     }
124 
125     /* Patch in appropriate value for AppleSMC _STA */
126     *(uint8_t *)(info->dsdt_code + *applesmc_sta) =
127         applesmc_find() ? 0x0b : 0x00;
128 }
129 
130 static
131 int acpi_add_cpu_info(Object *o, void *opaque)
132 {
133     AcpiCpuInfo *cpu = opaque;
134     uint64_t apic_id;
135 
136     if (object_dynamic_cast(o, TYPE_CPU)) {
137         apic_id = object_property_get_int(o, "apic-id", NULL);
138         assert(apic_id < ACPI_CPU_HOTPLUG_ID_LIMIT);
139 
140         set_bit(apic_id, cpu->found_cpus);
141     }
142 
143     object_child_foreach(o, acpi_add_cpu_info, opaque);
144     return 0;
145 }
146 
147 static void acpi_get_cpu_info(AcpiCpuInfo *cpu)
148 {
149     Object *root = object_get_root();
150 
151     memset(cpu->found_cpus, 0, sizeof cpu->found_cpus);
152     object_child_foreach(root, acpi_add_cpu_info, cpu);
153 }
154 
155 static void acpi_get_pm_info(AcpiPmInfo *pm)
156 {
157     Object *piix = piix4_pm_find();
158     Object *lpc = ich9_lpc_find();
159     Object *obj = NULL;
160     QObject *o;
161 
162     if (piix) {
163         obj = piix;
164     }
165     if (lpc) {
166         obj = lpc;
167     }
168     assert(obj);
169 
170     /* Fill in optional s3/s4 related properties */
171     o = object_property_get_qobject(obj, ACPI_PM_PROP_S3_DISABLED, NULL);
172     if (o) {
173         pm->s3_disabled = qint_get_int(qobject_to_qint(o));
174     } else {
175         pm->s3_disabled = false;
176     }
177     qobject_decref(o);
178     o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL);
179     if (o) {
180         pm->s4_disabled = qint_get_int(qobject_to_qint(o));
181     } else {
182         pm->s4_disabled = false;
183     }
184     qobject_decref(o);
185     o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL);
186     if (o) {
187         pm->s4_val = qint_get_int(qobject_to_qint(o));
188     } else {
189         pm->s4_val = false;
190     }
191     qobject_decref(o);
192 
193     /* Fill in mandatory properties */
194     pm->sci_int = object_property_get_int(obj, ACPI_PM_PROP_SCI_INT, NULL);
195 
196     pm->acpi_enable_cmd = object_property_get_int(obj,
197                                                   ACPI_PM_PROP_ACPI_ENABLE_CMD,
198                                                   NULL);
199     pm->acpi_disable_cmd = object_property_get_int(obj,
200                                                   ACPI_PM_PROP_ACPI_DISABLE_CMD,
201                                                   NULL);
202     pm->io_base = object_property_get_int(obj, ACPI_PM_PROP_PM_IO_BASE,
203                                           NULL);
204     pm->gpe0_blk = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK,
205                                            NULL);
206     pm->gpe0_blk_len = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK_LEN,
207                                                NULL);
208     pm->pcihp_bridge_en =
209         object_property_get_bool(obj, "acpi-pci-hotplug-with-bridge-support",
210                                  NULL);
211 }
212 
213 static void acpi_get_misc_info(AcpiMiscInfo *info)
214 {
215     info->has_hpet = hpet_find();
216     info->has_tpm = tpm_find();
217     info->pvpanic_port = pvpanic_port();
218 }
219 
220 static void acpi_get_pci_info(PcPciInfo *info)
221 {
222     Object *pci_host;
223     bool ambiguous;
224 
225     pci_host = object_resolve_path_type("", TYPE_PCI_HOST_BRIDGE, &ambiguous);
226     g_assert(!ambiguous);
227     g_assert(pci_host);
228 
229     info->w32.begin = object_property_get_int(pci_host,
230                                               PCI_HOST_PROP_PCI_HOLE_START,
231                                               NULL);
232     info->w32.end = object_property_get_int(pci_host,
233                                             PCI_HOST_PROP_PCI_HOLE_END,
234                                             NULL);
235     info->w64.begin = object_property_get_int(pci_host,
236                                               PCI_HOST_PROP_PCI_HOLE64_START,
237                                               NULL);
238     info->w64.end = object_property_get_int(pci_host,
239                                             PCI_HOST_PROP_PCI_HOLE64_END,
240                                             NULL);
241 }
242 
243 #define ACPI_BUILD_APPNAME  "Bochs"
244 #define ACPI_BUILD_APPNAME6 "BOCHS "
245 #define ACPI_BUILD_APPNAME4 "BXPC"
246 
247 #define ACPI_BUILD_DPRINTF(level, fmt, ...) do {} while (0)
248 
249 #define ACPI_BUILD_TABLE_FILE "etc/acpi/tables"
250 #define ACPI_BUILD_RSDP_FILE "etc/acpi/rsdp"
251 
252 static void
253 build_header(GArray *linker, GArray *table_data,
254              AcpiTableHeader *h, const char *sig, int len, uint8_t rev)
255 {
256     memcpy(&h->signature, sig, 4);
257     h->length = cpu_to_le32(len);
258     h->revision = rev;
259     memcpy(h->oem_id, ACPI_BUILD_APPNAME6, 6);
260     memcpy(h->oem_table_id, ACPI_BUILD_APPNAME4, 4);
261     memcpy(h->oem_table_id + 4, sig, 4);
262     h->oem_revision = cpu_to_le32(1);
263     memcpy(h->asl_compiler_id, ACPI_BUILD_APPNAME4, 4);
264     h->asl_compiler_revision = cpu_to_le32(1);
265     h->checksum = 0;
266     /* Checksum to be filled in by Guest linker */
267     bios_linker_loader_add_checksum(linker, ACPI_BUILD_TABLE_FILE,
268                                     table_data->data, h, len, &h->checksum);
269 }
270 
271 static inline GArray *build_alloc_array(void)
272 {
273         return g_array_new(false, true /* clear */, 1);
274 }
275 
276 static inline void build_free_array(GArray *array)
277 {
278         g_array_free(array, true);
279 }
280 
281 static inline void build_prepend_byte(GArray *array, uint8_t val)
282 {
283     g_array_prepend_val(array, val);
284 }
285 
286 static inline void build_append_byte(GArray *array, uint8_t val)
287 {
288     g_array_append_val(array, val);
289 }
290 
291 static inline void build_append_array(GArray *array, GArray *val)
292 {
293     g_array_append_vals(array, val->data, val->len);
294 }
295 
296 static void GCC_FMT_ATTR(2, 3)
297 build_append_nameseg(GArray *array, const char *format, ...)
298 {
299     /* It would be nicer to use g_string_vprintf but it's only there in 2.22 */
300     char s[] = "XXXX";
301     int len;
302     va_list args;
303 
304     va_start(args, format);
305     len = vsnprintf(s, sizeof s, format, args);
306     va_end(args);
307 
308     assert(len == 4);
309     g_array_append_vals(array, s, len);
310 }
311 
312 /* 5.4 Definition Block Encoding */
313 enum {
314     PACKAGE_LENGTH_1BYTE_SHIFT = 6, /* Up to 63 - use extra 2 bits. */
315     PACKAGE_LENGTH_2BYTE_SHIFT = 4,
316     PACKAGE_LENGTH_3BYTE_SHIFT = 12,
317     PACKAGE_LENGTH_4BYTE_SHIFT = 20,
318 };
319 
320 static void build_prepend_package_length(GArray *package, unsigned min_bytes)
321 {
322     uint8_t byte;
323     unsigned length = package->len;
324     unsigned length_bytes;
325 
326     if (length + 1 < (1 << PACKAGE_LENGTH_1BYTE_SHIFT)) {
327         length_bytes = 1;
328     } else if (length + 2 < (1 << PACKAGE_LENGTH_3BYTE_SHIFT)) {
329         length_bytes = 2;
330     } else if (length + 3 < (1 << PACKAGE_LENGTH_4BYTE_SHIFT)) {
331         length_bytes = 3;
332     } else {
333         length_bytes = 4;
334     }
335 
336     /* Force length to at least min_bytes.
337      * This wastes memory but that's how bios did it.
338      */
339     length_bytes = MAX(length_bytes, min_bytes);
340 
341     /* PkgLength is the length of the inclusive length of the data. */
342     length += length_bytes;
343 
344     switch (length_bytes) {
345     case 1:
346         byte = length;
347         build_prepend_byte(package, byte);
348         return;
349     case 4:
350         byte = length >> PACKAGE_LENGTH_4BYTE_SHIFT;
351         build_prepend_byte(package, byte);
352         length &= (1 << PACKAGE_LENGTH_4BYTE_SHIFT) - 1;
353         /* fall through */
354     case 3:
355         byte = length >> PACKAGE_LENGTH_3BYTE_SHIFT;
356         build_prepend_byte(package, byte);
357         length &= (1 << PACKAGE_LENGTH_3BYTE_SHIFT) - 1;
358         /* fall through */
359     case 2:
360         byte = length >> PACKAGE_LENGTH_2BYTE_SHIFT;
361         build_prepend_byte(package, byte);
362         length &= (1 << PACKAGE_LENGTH_2BYTE_SHIFT) - 1;
363         /* fall through */
364     }
365     /*
366      * Most significant two bits of byte zero indicate how many following bytes
367      * are in PkgLength encoding.
368      */
369     byte = ((length_bytes - 1) << PACKAGE_LENGTH_1BYTE_SHIFT) | length;
370     build_prepend_byte(package, byte);
371 }
372 
373 static void build_package(GArray *package, uint8_t op, unsigned min_bytes)
374 {
375     build_prepend_package_length(package, min_bytes);
376     build_prepend_byte(package, op);
377 }
378 
379 static void build_extop_package(GArray *package, uint8_t op)
380 {
381     build_package(package, op, 1);
382     build_prepend_byte(package, 0x5B); /* ExtOpPrefix */
383 }
384 
385 static void build_append_value(GArray *table, uint32_t value, int size)
386 {
387     uint8_t prefix;
388     int i;
389 
390     switch (size) {
391     case 1:
392         prefix = 0x0A; /* BytePrefix */
393         break;
394     case 2:
395         prefix = 0x0B; /* WordPrefix */
396         break;
397     case 4:
398         prefix = 0x0C; /* DWordPrefix */
399         break;
400     default:
401         assert(0);
402         return;
403     }
404     build_append_byte(table, prefix);
405     for (i = 0; i < size; ++i) {
406         build_append_byte(table, value & 0xFF);
407         value = value >> 8;
408     }
409 }
410 
411 static void build_append_int(GArray *table, uint32_t value)
412 {
413     if (value == 0x00) {
414         build_append_byte(table, 0x00); /* ZeroOp */
415     } else if (value == 0x01) {
416         build_append_byte(table, 0x01); /* OneOp */
417     } else if (value <= 0xFF) {
418         build_append_value(table, value, 1);
419     } else if (value <= 0xFFFF) {
420         build_append_value(table, value, 2);
421     } else {
422         build_append_value(table, value, 4);
423     }
424 }
425 
426 static GArray *build_alloc_method(const char *name, uint8_t arg_count)
427 {
428     GArray *method = build_alloc_array();
429 
430     build_append_nameseg(method, "%s", name);
431     build_append_byte(method, arg_count); /* MethodFlags: ArgCount */
432 
433     return method;
434 }
435 
436 static void build_append_and_cleanup_method(GArray *device, GArray *method)
437 {
438     uint8_t op = 0x14; /* MethodOp */
439 
440     build_package(method, op, 0);
441 
442     build_append_array(device, method);
443     build_free_array(method);
444 }
445 
446 static void build_append_notify_target_ifequal(GArray *method,
447                                                GArray *target_name,
448                                                uint32_t value, int size)
449 {
450     GArray *notify = build_alloc_array();
451     uint8_t op = 0xA0; /* IfOp */
452 
453     build_append_byte(notify, 0x93); /* LEqualOp */
454     build_append_byte(notify, 0x68); /* Arg0Op */
455     build_append_value(notify, value, size);
456     build_append_byte(notify, 0x86); /* NotifyOp */
457     build_append_array(notify, target_name);
458     build_append_byte(notify, 0x69); /* Arg1Op */
459 
460     /* Pack it up */
461     build_package(notify, op, 1);
462 
463     build_append_array(method, notify);
464 
465     build_free_array(notify);
466 }
467 
468 /* End here */
469 #define ACPI_PORT_SMI_CMD           0x00b2 /* TODO: this is APM_CNT_IOPORT */
470 
471 static inline void *acpi_data_push(GArray *table_data, unsigned size)
472 {
473     unsigned off = table_data->len;
474     g_array_set_size(table_data, off + size);
475     return table_data->data + off;
476 }
477 
478 static unsigned acpi_data_len(GArray *table)
479 {
480 #if GLIB_CHECK_VERSION(2, 22, 0)
481     assert(g_array_get_element_size(table) == 1);
482 #endif
483     return table->len;
484 }
485 
486 static void acpi_align_size(GArray *blob, unsigned align)
487 {
488     /* Align size to multiple of given size. This reduces the chance
489      * we need to change size in the future (breaking cross version migration).
490      */
491     g_array_set_size(blob, ROUND_UP(acpi_data_len(blob), align));
492 }
493 
494 /* Set a value within table in a safe manner */
495 #define ACPI_BUILD_SET_LE(table, size, off, bits, val) \
496     do { \
497         uint64_t ACPI_BUILD_SET_LE_val = cpu_to_le64(val); \
498         memcpy(acpi_data_get_ptr(table, size, off, \
499                                  (bits) / BITS_PER_BYTE), \
500                &ACPI_BUILD_SET_LE_val, \
501                (bits) / BITS_PER_BYTE); \
502     } while (0)
503 
504 static inline void *acpi_data_get_ptr(uint8_t *table_data, unsigned table_size,
505                                       unsigned off, unsigned size)
506 {
507     assert(off + size > off);
508     assert(off + size <= table_size);
509     return table_data + off;
510 }
511 
512 static inline void acpi_add_table(GArray *table_offsets, GArray *table_data)
513 {
514     uint32_t offset = cpu_to_le32(table_data->len);
515     g_array_append_val(table_offsets, offset);
516 }
517 
518 /* FACS */
519 static void
520 build_facs(GArray *table_data, GArray *linker, PcGuestInfo *guest_info)
521 {
522     AcpiFacsDescriptorRev1 *facs = acpi_data_push(table_data, sizeof *facs);
523     memcpy(&facs->signature, "FACS", 4);
524     facs->length = cpu_to_le32(sizeof(*facs));
525 }
526 
527 /* Load chipset information in FADT */
528 static void fadt_setup(AcpiFadtDescriptorRev1 *fadt, AcpiPmInfo *pm)
529 {
530     fadt->model = 1;
531     fadt->reserved1 = 0;
532     fadt->sci_int = cpu_to_le16(pm->sci_int);
533     fadt->smi_cmd = cpu_to_le32(ACPI_PORT_SMI_CMD);
534     fadt->acpi_enable = pm->acpi_enable_cmd;
535     fadt->acpi_disable = pm->acpi_disable_cmd;
536     /* EVT, CNT, TMR offset matches hw/acpi/core.c */
537     fadt->pm1a_evt_blk = cpu_to_le32(pm->io_base);
538     fadt->pm1a_cnt_blk = cpu_to_le32(pm->io_base + 0x04);
539     fadt->pm_tmr_blk = cpu_to_le32(pm->io_base + 0x08);
540     fadt->gpe0_blk = cpu_to_le32(pm->gpe0_blk);
541     /* EVT, CNT, TMR length matches hw/acpi/core.c */
542     fadt->pm1_evt_len = 4;
543     fadt->pm1_cnt_len = 2;
544     fadt->pm_tmr_len = 4;
545     fadt->gpe0_blk_len = pm->gpe0_blk_len;
546     fadt->plvl2_lat = cpu_to_le16(0xfff); /* C2 state not supported */
547     fadt->plvl3_lat = cpu_to_le16(0xfff); /* C3 state not supported */
548     fadt->flags = cpu_to_le32((1 << ACPI_FADT_F_WBINVD) |
549                               (1 << ACPI_FADT_F_PROC_C1) |
550                               (1 << ACPI_FADT_F_SLP_BUTTON) |
551                               (1 << ACPI_FADT_F_RTC_S4));
552     fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_USE_PLATFORM_CLOCK);
553 }
554 
555 
556 /* FADT */
557 static void
558 build_fadt(GArray *table_data, GArray *linker, AcpiPmInfo *pm,
559            unsigned facs, unsigned dsdt)
560 {
561     AcpiFadtDescriptorRev1 *fadt = acpi_data_push(table_data, sizeof(*fadt));
562 
563     fadt->firmware_ctrl = cpu_to_le32(facs);
564     /* FACS address to be filled by Guest linker */
565     bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,
566                                    ACPI_BUILD_TABLE_FILE,
567                                    table_data, &fadt->firmware_ctrl,
568                                    sizeof fadt->firmware_ctrl);
569 
570     fadt->dsdt = cpu_to_le32(dsdt);
571     /* DSDT address to be filled by Guest linker */
572     bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,
573                                    ACPI_BUILD_TABLE_FILE,
574                                    table_data, &fadt->dsdt,
575                                    sizeof fadt->dsdt);
576 
577     fadt_setup(fadt, pm);
578 
579     build_header(linker, table_data,
580                  (void *)fadt, "FACP", sizeof(*fadt), 1);
581 }
582 
583 static void
584 build_madt(GArray *table_data, GArray *linker, AcpiCpuInfo *cpu,
585            PcGuestInfo *guest_info)
586 {
587     int madt_start = table_data->len;
588 
589     AcpiMultipleApicTable *madt;
590     AcpiMadtIoApic *io_apic;
591     AcpiMadtIntsrcovr *intsrcovr;
592     AcpiMadtLocalNmi *local_nmi;
593     int i;
594 
595     madt = acpi_data_push(table_data, sizeof *madt);
596     madt->local_apic_address = cpu_to_le32(APIC_DEFAULT_ADDRESS);
597     madt->flags = cpu_to_le32(1);
598 
599     for (i = 0; i < guest_info->apic_id_limit; i++) {
600         AcpiMadtProcessorApic *apic = acpi_data_push(table_data, sizeof *apic);
601         apic->type = ACPI_APIC_PROCESSOR;
602         apic->length = sizeof(*apic);
603         apic->processor_id = i;
604         apic->local_apic_id = i;
605         if (test_bit(i, cpu->found_cpus)) {
606             apic->flags = cpu_to_le32(1);
607         } else {
608             apic->flags = cpu_to_le32(0);
609         }
610     }
611     io_apic = acpi_data_push(table_data, sizeof *io_apic);
612     io_apic->type = ACPI_APIC_IO;
613     io_apic->length = sizeof(*io_apic);
614 #define ACPI_BUILD_IOAPIC_ID 0x0
615     io_apic->io_apic_id = ACPI_BUILD_IOAPIC_ID;
616     io_apic->address = cpu_to_le32(IO_APIC_DEFAULT_ADDRESS);
617     io_apic->interrupt = cpu_to_le32(0);
618 
619     if (guest_info->apic_xrupt_override) {
620         intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);
621         intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;
622         intsrcovr->length = sizeof(*intsrcovr);
623         intsrcovr->source = 0;
624         intsrcovr->gsi    = cpu_to_le32(2);
625         intsrcovr->flags  = cpu_to_le16(0); /* conforms to bus specifications */
626     }
627     for (i = 1; i < 16; i++) {
628 #define ACPI_BUILD_PCI_IRQS ((1<<5) | (1<<9) | (1<<10) | (1<<11))
629         if (!(ACPI_BUILD_PCI_IRQS & (1 << i))) {
630             /* No need for a INT source override structure. */
631             continue;
632         }
633         intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);
634         intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;
635         intsrcovr->length = sizeof(*intsrcovr);
636         intsrcovr->source = i;
637         intsrcovr->gsi    = cpu_to_le32(i);
638         intsrcovr->flags  = cpu_to_le16(0xd); /* active high, level triggered */
639     }
640 
641     local_nmi = acpi_data_push(table_data, sizeof *local_nmi);
642     local_nmi->type         = ACPI_APIC_LOCAL_NMI;
643     local_nmi->length       = sizeof(*local_nmi);
644     local_nmi->processor_id = 0xff; /* all processors */
645     local_nmi->flags        = cpu_to_le16(0);
646     local_nmi->lint         = 1; /* ACPI_LINT1 */
647 
648     build_header(linker, table_data,
649                  (void *)(table_data->data + madt_start), "APIC",
650                  table_data->len - madt_start, 1);
651 }
652 
653 /* Encode a hex value */
654 static inline char acpi_get_hex(uint32_t val)
655 {
656     val &= 0x0f;
657     return (val <= 9) ? ('0' + val) : ('A' + val - 10);
658 }
659 
660 #include "hw/i386/ssdt-proc.hex"
661 
662 /* 0x5B 0x83 ProcessorOp PkgLength NameString ProcID */
663 #define ACPI_PROC_OFFSET_CPUHEX (*ssdt_proc_name - *ssdt_proc_start + 2)
664 #define ACPI_PROC_OFFSET_CPUID1 (*ssdt_proc_name - *ssdt_proc_start + 4)
665 #define ACPI_PROC_OFFSET_CPUID2 (*ssdt_proc_id - *ssdt_proc_start)
666 #define ACPI_PROC_SIZEOF (*ssdt_proc_end - *ssdt_proc_start)
667 #define ACPI_PROC_AML (ssdp_proc_aml + *ssdt_proc_start)
668 
669 /* 0x5B 0x82 DeviceOp PkgLength NameString */
670 #define ACPI_PCIHP_OFFSET_HEX (*ssdt_pcihp_name - *ssdt_pcihp_start + 1)
671 #define ACPI_PCIHP_OFFSET_ID (*ssdt_pcihp_id - *ssdt_pcihp_start)
672 #define ACPI_PCIHP_OFFSET_ADR (*ssdt_pcihp_adr - *ssdt_pcihp_start)
673 #define ACPI_PCIHP_OFFSET_EJ0 (*ssdt_pcihp_ej0 - *ssdt_pcihp_start)
674 #define ACPI_PCIHP_SIZEOF (*ssdt_pcihp_end - *ssdt_pcihp_start)
675 #define ACPI_PCIHP_AML (ssdp_pcihp_aml + *ssdt_pcihp_start)
676 
677 #define ACPI_PCINOHP_OFFSET_HEX (*ssdt_pcinohp_name - *ssdt_pcinohp_start + 1)
678 #define ACPI_PCINOHP_OFFSET_ADR (*ssdt_pcinohp_adr - *ssdt_pcinohp_start)
679 #define ACPI_PCINOHP_SIZEOF (*ssdt_pcinohp_end - *ssdt_pcinohp_start)
680 #define ACPI_PCINOHP_AML (ssdp_pcihp_aml + *ssdt_pcinohp_start)
681 
682 #define ACPI_PCIVGA_OFFSET_HEX (*ssdt_pcivga_name - *ssdt_pcivga_start + 1)
683 #define ACPI_PCIVGA_OFFSET_ADR (*ssdt_pcivga_adr - *ssdt_pcivga_start)
684 #define ACPI_PCIVGA_SIZEOF (*ssdt_pcivga_end - *ssdt_pcivga_start)
685 #define ACPI_PCIVGA_AML (ssdp_pcihp_aml + *ssdt_pcivga_start)
686 
687 #define ACPI_PCIQXL_OFFSET_HEX (*ssdt_pciqxl_name - *ssdt_pciqxl_start + 1)
688 #define ACPI_PCIQXL_OFFSET_ADR (*ssdt_pciqxl_adr - *ssdt_pciqxl_start)
689 #define ACPI_PCIQXL_SIZEOF (*ssdt_pciqxl_end - *ssdt_pciqxl_start)
690 #define ACPI_PCIQXL_AML (ssdp_pcihp_aml + *ssdt_pciqxl_start)
691 
692 #include "hw/i386/ssdt-mem.hex"
693 
694 /* 0x5B 0x82 DeviceOp PkgLength NameString DimmID */
695 #define ACPI_MEM_OFFSET_HEX (*ssdt_mem_name - *ssdt_mem_start + 2)
696 #define ACPI_MEM_OFFSET_ID (*ssdt_mem_id - *ssdt_mem_start + 7)
697 #define ACPI_MEM_SIZEOF (*ssdt_mem_end - *ssdt_mem_start)
698 #define ACPI_MEM_AML (ssdm_mem_aml + *ssdt_mem_start)
699 
700 #define ACPI_SSDT_SIGNATURE 0x54445353 /* SSDT */
701 #define ACPI_SSDT_HEADER_LENGTH 36
702 
703 #include "hw/i386/ssdt-misc.hex"
704 #include "hw/i386/ssdt-pcihp.hex"
705 #include "hw/i386/ssdt-tpm.hex"
706 
707 static void
708 build_append_notify_method(GArray *device, const char *name,
709                            const char *format, int count)
710 {
711     int i;
712     GArray *method = build_alloc_method(name, 2);
713 
714     for (i = 0; i < count; i++) {
715         GArray *target = build_alloc_array();
716         build_append_nameseg(target, format, i);
717         assert(i < 256); /* Fits in 1 byte */
718         build_append_notify_target_ifequal(method, target, i, 1);
719         build_free_array(target);
720     }
721 
722     build_append_and_cleanup_method(device, method);
723 }
724 
725 static void patch_pcihp(int slot, uint8_t *ssdt_ptr)
726 {
727     unsigned devfn = PCI_DEVFN(slot, 0);
728 
729     ssdt_ptr[ACPI_PCIHP_OFFSET_HEX] = acpi_get_hex(devfn >> 4);
730     ssdt_ptr[ACPI_PCIHP_OFFSET_HEX + 1] = acpi_get_hex(devfn);
731     ssdt_ptr[ACPI_PCIHP_OFFSET_ID] = slot;
732     ssdt_ptr[ACPI_PCIHP_OFFSET_ADR + 2] = slot;
733 }
734 
735 static void patch_pcinohp(int slot, uint8_t *ssdt_ptr)
736 {
737     unsigned devfn = PCI_DEVFN(slot, 0);
738 
739     ssdt_ptr[ACPI_PCINOHP_OFFSET_HEX] = acpi_get_hex(devfn >> 4);
740     ssdt_ptr[ACPI_PCINOHP_OFFSET_HEX + 1] = acpi_get_hex(devfn);
741     ssdt_ptr[ACPI_PCINOHP_OFFSET_ADR + 2] = slot;
742 }
743 
744 static void patch_pcivga(int slot, uint8_t *ssdt_ptr)
745 {
746     unsigned devfn = PCI_DEVFN(slot, 0);
747 
748     ssdt_ptr[ACPI_PCIVGA_OFFSET_HEX] = acpi_get_hex(devfn >> 4);
749     ssdt_ptr[ACPI_PCIVGA_OFFSET_HEX + 1] = acpi_get_hex(devfn);
750     ssdt_ptr[ACPI_PCIVGA_OFFSET_ADR + 2] = slot;
751 }
752 
753 static void patch_pciqxl(int slot, uint8_t *ssdt_ptr)
754 {
755     unsigned devfn = PCI_DEVFN(slot, 0);
756 
757     ssdt_ptr[ACPI_PCIQXL_OFFSET_HEX] = acpi_get_hex(devfn >> 4);
758     ssdt_ptr[ACPI_PCIQXL_OFFSET_HEX + 1] = acpi_get_hex(devfn);
759     ssdt_ptr[ACPI_PCIQXL_OFFSET_ADR + 2] = slot;
760 }
761 
762 /* Assign BSEL property to all buses.  In the future, this can be changed
763  * to only assign to buses that support hotplug.
764  */
765 static void *acpi_set_bsel(PCIBus *bus, void *opaque)
766 {
767     unsigned *bsel_alloc = opaque;
768     unsigned *bus_bsel;
769 
770     if (bus->qbus.allow_hotplug) {
771         bus_bsel = g_malloc(sizeof *bus_bsel);
772 
773         *bus_bsel = (*bsel_alloc)++;
774         object_property_add_uint32_ptr(OBJECT(bus), ACPI_PCIHP_PROP_BSEL,
775                                        bus_bsel, NULL);
776     }
777 
778     return bsel_alloc;
779 }
780 
781 static void acpi_set_pci_info(void)
782 {
783     PCIBus *bus = find_i440fx(); /* TODO: Q35 support */
784     unsigned bsel_alloc = 0;
785 
786     if (bus) {
787         /* Scan all PCI buses. Set property to enable acpi based hotplug. */
788         pci_for_each_bus_depth_first(bus, acpi_set_bsel, NULL, &bsel_alloc);
789     }
790 }
791 
792 static void build_pci_bus_state_init(AcpiBuildPciBusHotplugState *state,
793                                      AcpiBuildPciBusHotplugState *parent,
794                                      bool pcihp_bridge_en)
795 {
796     state->parent = parent;
797     state->device_table = build_alloc_array();
798     state->notify_table = build_alloc_array();
799     state->pcihp_bridge_en = pcihp_bridge_en;
800 }
801 
802 static void build_pci_bus_state_cleanup(AcpiBuildPciBusHotplugState *state)
803 {
804     build_free_array(state->device_table);
805     build_free_array(state->notify_table);
806 }
807 
808 static void *build_pci_bus_begin(PCIBus *bus, void *parent_state)
809 {
810     AcpiBuildPciBusHotplugState *parent = parent_state;
811     AcpiBuildPciBusHotplugState *child = g_malloc(sizeof *child);
812 
813     build_pci_bus_state_init(child, parent, parent->pcihp_bridge_en);
814 
815     return child;
816 }
817 
818 static void build_pci_bus_end(PCIBus *bus, void *bus_state)
819 {
820     AcpiBuildPciBusHotplugState *child = bus_state;
821     AcpiBuildPciBusHotplugState *parent = child->parent;
822     GArray *bus_table = build_alloc_array();
823     DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX);
824     DECLARE_BITMAP(slot_device_present, PCI_SLOT_MAX);
825     DECLARE_BITMAP(slot_device_system, PCI_SLOT_MAX);
826     DECLARE_BITMAP(slot_device_vga, PCI_SLOT_MAX);
827     DECLARE_BITMAP(slot_device_qxl, PCI_SLOT_MAX);
828     uint8_t op;
829     int i;
830     QObject *bsel;
831     GArray *method;
832     bool bus_hotplug_support = false;
833 
834     /*
835      * Skip bridge subtree creation if bridge hotplug is disabled
836      * to make acpi tables compatible with legacy machine types.
837      */
838     if (!child->pcihp_bridge_en && bus->parent_dev) {
839         return;
840     }
841 
842     if (bus->parent_dev) {
843         op = 0x82; /* DeviceOp */
844         build_append_nameseg(bus_table, "S%.02X_",
845                              bus->parent_dev->devfn);
846         build_append_byte(bus_table, 0x08); /* NameOp */
847         build_append_nameseg(bus_table, "_SUN");
848         build_append_value(bus_table, PCI_SLOT(bus->parent_dev->devfn), 1);
849         build_append_byte(bus_table, 0x08); /* NameOp */
850         build_append_nameseg(bus_table, "_ADR");
851         build_append_value(bus_table, (PCI_SLOT(bus->parent_dev->devfn) << 16) |
852                            PCI_FUNC(bus->parent_dev->devfn), 4);
853     } else {
854         op = 0x10; /* ScopeOp */;
855         build_append_nameseg(bus_table, "PCI0");
856     }
857 
858     bsel = object_property_get_qobject(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, NULL);
859     if (bsel) {
860         build_append_byte(bus_table, 0x08); /* NameOp */
861         build_append_nameseg(bus_table, "BSEL");
862         build_append_int(bus_table, qint_get_int(qobject_to_qint(bsel)));
863         memset(slot_hotplug_enable, 0xff, sizeof slot_hotplug_enable);
864     } else {
865         /* No bsel - no slots are hot-pluggable */
866         memset(slot_hotplug_enable, 0x00, sizeof slot_hotplug_enable);
867     }
868 
869     memset(slot_device_present, 0x00, sizeof slot_device_present);
870     memset(slot_device_system, 0x00, sizeof slot_device_present);
871     memset(slot_device_vga, 0x00, sizeof slot_device_vga);
872     memset(slot_device_qxl, 0x00, sizeof slot_device_qxl);
873 
874     for (i = 0; i < ARRAY_SIZE(bus->devices); i += PCI_FUNC_MAX) {
875         DeviceClass *dc;
876         PCIDeviceClass *pc;
877         PCIDevice *pdev = bus->devices[i];
878         int slot = PCI_SLOT(i);
879         bool bridge_in_acpi;
880 
881         if (!pdev) {
882             continue;
883         }
884 
885         set_bit(slot, slot_device_present);
886         pc = PCI_DEVICE_GET_CLASS(pdev);
887         dc = DEVICE_GET_CLASS(pdev);
888 
889         /* When hotplug for bridges is enabled, bridges are
890          * described in ACPI separately (see build_pci_bus_end).
891          * In this case they aren't themselves hot-pluggable.
892          */
893         bridge_in_acpi = pc->is_bridge && child->pcihp_bridge_en;
894 
895         if (pc->class_id == PCI_CLASS_BRIDGE_ISA || bridge_in_acpi) {
896             set_bit(slot, slot_device_system);
897         }
898 
899         if (pc->class_id == PCI_CLASS_DISPLAY_VGA) {
900             set_bit(slot, slot_device_vga);
901 
902             if (object_dynamic_cast(OBJECT(pdev), "qxl-vga")) {
903                 set_bit(slot, slot_device_qxl);
904             }
905         }
906 
907         if (!dc->hotpluggable || bridge_in_acpi) {
908             clear_bit(slot, slot_hotplug_enable);
909         }
910     }
911 
912     /* Append Device object for each slot */
913     for (i = 0; i < PCI_SLOT_MAX; i++) {
914         bool can_eject = test_bit(i, slot_hotplug_enable);
915         bool present = test_bit(i, slot_device_present);
916         bool vga = test_bit(i, slot_device_vga);
917         bool qxl = test_bit(i, slot_device_qxl);
918         bool system = test_bit(i, slot_device_system);
919         if (can_eject) {
920             void *pcihp = acpi_data_push(bus_table,
921                                          ACPI_PCIHP_SIZEOF);
922             memcpy(pcihp, ACPI_PCIHP_AML, ACPI_PCIHP_SIZEOF);
923             patch_pcihp(i, pcihp);
924             bus_hotplug_support = true;
925         } else if (qxl) {
926             void *pcihp = acpi_data_push(bus_table,
927                                          ACPI_PCIQXL_SIZEOF);
928             memcpy(pcihp, ACPI_PCIQXL_AML, ACPI_PCIQXL_SIZEOF);
929             patch_pciqxl(i, pcihp);
930         } else if (vga) {
931             void *pcihp = acpi_data_push(bus_table,
932                                          ACPI_PCIVGA_SIZEOF);
933             memcpy(pcihp, ACPI_PCIVGA_AML, ACPI_PCIVGA_SIZEOF);
934             patch_pcivga(i, pcihp);
935         } else if (system) {
936             /* Nothing to do: system devices are in DSDT or in SSDT above. */
937         } else if (present) {
938             void *pcihp = acpi_data_push(bus_table,
939                                          ACPI_PCINOHP_SIZEOF);
940             memcpy(pcihp, ACPI_PCINOHP_AML, ACPI_PCINOHP_SIZEOF);
941             patch_pcinohp(i, pcihp);
942         }
943     }
944 
945     if (bsel) {
946         method = build_alloc_method("DVNT", 2);
947 
948         for (i = 0; i < PCI_SLOT_MAX; i++) {
949             GArray *notify;
950             uint8_t op;
951 
952             if (!test_bit(i, slot_hotplug_enable)) {
953                 continue;
954             }
955 
956             notify = build_alloc_array();
957             op = 0xA0; /* IfOp */
958 
959             build_append_byte(notify, 0x7B); /* AndOp */
960             build_append_byte(notify, 0x68); /* Arg0Op */
961             build_append_int(notify, 0x1U << i);
962             build_append_byte(notify, 0x00); /* NullName */
963             build_append_byte(notify, 0x86); /* NotifyOp */
964             build_append_nameseg(notify, "S%.02X_", PCI_DEVFN(i, 0));
965             build_append_byte(notify, 0x69); /* Arg1Op */
966 
967             /* Pack it up */
968             build_package(notify, op, 0);
969 
970             build_append_array(method, notify);
971 
972             build_free_array(notify);
973         }
974 
975         build_append_and_cleanup_method(bus_table, method);
976     }
977 
978     /* Append PCNT method to notify about events on local and child buses.
979      * Add unconditionally for root since DSDT expects it.
980      */
981     if (bus_hotplug_support || child->notify_table->len || !bus->parent_dev) {
982         method = build_alloc_method("PCNT", 0);
983 
984         /* If bus supports hotplug select it and notify about local events */
985         if (bsel) {
986             build_append_byte(method, 0x70); /* StoreOp */
987             build_append_int(method, qint_get_int(qobject_to_qint(bsel)));
988             build_append_nameseg(method, "BNUM");
989             build_append_nameseg(method, "DVNT");
990             build_append_nameseg(method, "PCIU");
991             build_append_int(method, 1); /* Device Check */
992             build_append_nameseg(method, "DVNT");
993             build_append_nameseg(method, "PCID");
994             build_append_int(method, 3); /* Eject Request */
995         }
996 
997         /* Notify about child bus events in any case */
998         build_append_array(method, child->notify_table);
999 
1000         build_append_and_cleanup_method(bus_table, method);
1001 
1002         /* Append description of child buses */
1003         build_append_array(bus_table, child->device_table);
1004 
1005         /* Pack it up */
1006         if (bus->parent_dev) {
1007             build_extop_package(bus_table, op);
1008         } else {
1009             build_package(bus_table, op, 0);
1010         }
1011 
1012         /* Append our bus description to parent table */
1013         build_append_array(parent->device_table, bus_table);
1014 
1015         /* Also tell parent how to notify us, invoking PCNT method.
1016          * At the moment this is not needed for root as we have a single root.
1017          */
1018         if (bus->parent_dev) {
1019             build_append_byte(parent->notify_table, '^'); /* ParentPrefixChar */
1020             build_append_byte(parent->notify_table, 0x2E); /* DualNamePrefix */
1021             build_append_nameseg(parent->notify_table, "S%.02X_",
1022                                  bus->parent_dev->devfn);
1023             build_append_nameseg(parent->notify_table, "PCNT");
1024         }
1025     }
1026 
1027     qobject_decref(bsel);
1028     build_free_array(bus_table);
1029     build_pci_bus_state_cleanup(child);
1030     g_free(child);
1031 }
1032 
1033 static void patch_pci_windows(PcPciInfo *pci, uint8_t *start, unsigned size)
1034 {
1035     ACPI_BUILD_SET_LE(start, size, acpi_pci32_start[0], 32, pci->w32.begin);
1036 
1037     ACPI_BUILD_SET_LE(start, size, acpi_pci32_end[0], 32, pci->w32.end - 1);
1038 
1039     if (pci->w64.end || pci->w64.begin) {
1040         ACPI_BUILD_SET_LE(start, size, acpi_pci64_valid[0], 8, 1);
1041         ACPI_BUILD_SET_LE(start, size, acpi_pci64_start[0], 64, pci->w64.begin);
1042         ACPI_BUILD_SET_LE(start, size, acpi_pci64_end[0], 64, pci->w64.end - 1);
1043         ACPI_BUILD_SET_LE(start, size, acpi_pci64_length[0], 64, pci->w64.end - pci->w64.begin);
1044     } else {
1045         ACPI_BUILD_SET_LE(start, size, acpi_pci64_valid[0], 8, 0);
1046     }
1047 }
1048 
1049 static void
1050 build_ssdt(GArray *table_data, GArray *linker,
1051            AcpiCpuInfo *cpu, AcpiPmInfo *pm, AcpiMiscInfo *misc,
1052            PcPciInfo *pci, PcGuestInfo *guest_info)
1053 {
1054     MachineState *machine = MACHINE(qdev_get_machine());
1055     uint32_t nr_mem = machine->ram_slots;
1056     unsigned acpi_cpus = guest_info->apic_id_limit;
1057     int ssdt_start = table_data->len;
1058     uint8_t *ssdt_ptr;
1059     int i;
1060 
1061     /* The current AML generator can cover the APIC ID range [0..255],
1062      * inclusive, for VCPU hotplug. */
1063     QEMU_BUILD_BUG_ON(ACPI_CPU_HOTPLUG_ID_LIMIT > 256);
1064     g_assert(acpi_cpus <= ACPI_CPU_HOTPLUG_ID_LIMIT);
1065 
1066     /* Copy header and patch values in the S3_ / S4_ / S5_ packages */
1067     ssdt_ptr = acpi_data_push(table_data, sizeof(ssdp_misc_aml));
1068     memcpy(ssdt_ptr, ssdp_misc_aml, sizeof(ssdp_misc_aml));
1069     if (pm->s3_disabled) {
1070         ssdt_ptr[acpi_s3_name[0]] = 'X';
1071     }
1072     if (pm->s4_disabled) {
1073         ssdt_ptr[acpi_s4_name[0]] = 'X';
1074     } else {
1075         ssdt_ptr[acpi_s4_pkg[0] + 1] = ssdt_ptr[acpi_s4_pkg[0] + 3] =
1076             pm->s4_val;
1077     }
1078 
1079     patch_pci_windows(pci, ssdt_ptr, sizeof(ssdp_misc_aml));
1080 
1081     ACPI_BUILD_SET_LE(ssdt_ptr, sizeof(ssdp_misc_aml),
1082                       ssdt_isa_pest[0], 16, misc->pvpanic_port);
1083 
1084     ACPI_BUILD_SET_LE(ssdt_ptr, sizeof(ssdp_misc_aml),
1085                       ssdt_mctrl_nr_slots[0], 32, nr_mem);
1086 
1087     {
1088         GArray *sb_scope = build_alloc_array();
1089         uint8_t op = 0x10; /* ScopeOp */
1090 
1091         build_append_nameseg(sb_scope, "_SB_");
1092 
1093         /* build Processor object for each processor */
1094         for (i = 0; i < acpi_cpus; i++) {
1095             uint8_t *proc = acpi_data_push(sb_scope, ACPI_PROC_SIZEOF);
1096             memcpy(proc, ACPI_PROC_AML, ACPI_PROC_SIZEOF);
1097             proc[ACPI_PROC_OFFSET_CPUHEX] = acpi_get_hex(i >> 4);
1098             proc[ACPI_PROC_OFFSET_CPUHEX+1] = acpi_get_hex(i);
1099             proc[ACPI_PROC_OFFSET_CPUID1] = i;
1100             proc[ACPI_PROC_OFFSET_CPUID2] = i;
1101         }
1102 
1103         /* build this code:
1104          *   Method(NTFY, 2) {If (LEqual(Arg0, 0x00)) {Notify(CP00, Arg1)} ...}
1105          */
1106         /* Arg0 = Processor ID = APIC ID */
1107         build_append_notify_method(sb_scope, "NTFY", "CP%0.02X", acpi_cpus);
1108 
1109         /* build "Name(CPON, Package() { One, One, ..., Zero, Zero, ... })" */
1110         build_append_byte(sb_scope, 0x08); /* NameOp */
1111         build_append_nameseg(sb_scope, "CPON");
1112 
1113         {
1114             GArray *package = build_alloc_array();
1115             uint8_t op;
1116 
1117             /*
1118              * Note: The ability to create variable-sized packages was first introduced in ACPI 2.0. ACPI 1.0 only
1119              * allowed fixed-size packages with up to 255 elements.
1120              * Windows guests up to win2k8 fail when VarPackageOp is used.
1121              */
1122             if (acpi_cpus <= 255) {
1123                 op = 0x12; /* PackageOp */
1124                 build_append_byte(package, acpi_cpus); /* NumElements */
1125             } else {
1126                 op = 0x13; /* VarPackageOp */
1127                 build_append_int(package, acpi_cpus); /* VarNumElements */
1128             }
1129 
1130             for (i = 0; i < acpi_cpus; i++) {
1131                 uint8_t b = test_bit(i, cpu->found_cpus) ? 0x01 : 0x00;
1132                 build_append_byte(package, b);
1133             }
1134 
1135             build_package(package, op, 2);
1136             build_append_array(sb_scope, package);
1137             build_free_array(package);
1138         }
1139 
1140         if (nr_mem) {
1141             assert(nr_mem <= ACPI_MAX_RAM_SLOTS);
1142             /* build memory devices */
1143             for (i = 0; i < nr_mem; i++) {
1144                 char id[3];
1145                 uint8_t *mem = acpi_data_push(sb_scope, ACPI_MEM_SIZEOF);
1146 
1147                 snprintf(id, sizeof(id), "%02X", i);
1148                 memcpy(mem, ACPI_MEM_AML, ACPI_MEM_SIZEOF);
1149                 memcpy(mem + ACPI_MEM_OFFSET_HEX, id, 2);
1150                 memcpy(mem + ACPI_MEM_OFFSET_ID, id, 2);
1151             }
1152 
1153             /* build Method(MEMORY_SLOT_NOTIFY_METHOD, 2) {
1154              *     If (LEqual(Arg0, 0x00)) {Notify(MP00, Arg1)} ...
1155              */
1156             build_append_notify_method(sb_scope,
1157                                        stringify(MEMORY_SLOT_NOTIFY_METHOD),
1158                                        "MP%0.02X", nr_mem);
1159         }
1160 
1161         {
1162             AcpiBuildPciBusHotplugState hotplug_state;
1163             Object *pci_host;
1164             PCIBus *bus = NULL;
1165             bool ambiguous;
1166 
1167             pci_host = object_resolve_path_type("", TYPE_PCI_HOST_BRIDGE, &ambiguous);
1168             if (!ambiguous && pci_host) {
1169                 bus = PCI_HOST_BRIDGE(pci_host)->bus;
1170             }
1171 
1172             build_pci_bus_state_init(&hotplug_state, NULL, pm->pcihp_bridge_en);
1173 
1174             if (bus) {
1175                 /* Scan all PCI buses. Generate tables to support hotplug. */
1176                 pci_for_each_bus_depth_first(bus, build_pci_bus_begin,
1177                                              build_pci_bus_end, &hotplug_state);
1178             }
1179 
1180             build_append_array(sb_scope, hotplug_state.device_table);
1181             build_pci_bus_state_cleanup(&hotplug_state);
1182         }
1183 
1184         build_package(sb_scope, op, 3);
1185         build_append_array(table_data, sb_scope);
1186         build_free_array(sb_scope);
1187     }
1188 
1189     build_header(linker, table_data,
1190                  (void *)(table_data->data + ssdt_start),
1191                  "SSDT", table_data->len - ssdt_start, 1);
1192 }
1193 
1194 static void
1195 build_hpet(GArray *table_data, GArray *linker)
1196 {
1197     Acpi20Hpet *hpet;
1198 
1199     hpet = acpi_data_push(table_data, sizeof(*hpet));
1200     /* Note timer_block_id value must be kept in sync with value advertised by
1201      * emulated hpet
1202      */
1203     hpet->timer_block_id = cpu_to_le32(0x8086a201);
1204     hpet->addr.address = cpu_to_le64(HPET_BASE);
1205     build_header(linker, table_data,
1206                  (void *)hpet, "HPET", sizeof(*hpet), 1);
1207 }
1208 
1209 static void
1210 build_tpm_tcpa(GArray *table_data, GArray *linker)
1211 {
1212     Acpi20Tcpa *tcpa = acpi_data_push(table_data, sizeof *tcpa);
1213     /* the log area will come right after the TCPA table */
1214     uint64_t log_area_start_address = acpi_data_len(table_data);
1215 
1216     tcpa->platform_class = cpu_to_le16(TPM_TCPA_ACPI_CLASS_CLIENT);
1217     tcpa->log_area_minimum_length = cpu_to_le32(TPM_LOG_AREA_MINIMUM_SIZE);
1218     tcpa->log_area_start_address = cpu_to_le64(log_area_start_address);
1219 
1220     /* log area start address to be filled by Guest linker */
1221     bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,
1222                                    ACPI_BUILD_TABLE_FILE,
1223                                    table_data, &tcpa->log_area_start_address,
1224                                    sizeof(tcpa->log_area_start_address));
1225 
1226     build_header(linker, table_data,
1227                  (void *)tcpa, "TCPA", sizeof(*tcpa), 2);
1228 
1229     /* now only get the log area and with that modify table_data */
1230     acpi_data_push(table_data, TPM_LOG_AREA_MINIMUM_SIZE);
1231 }
1232 
1233 static void
1234 build_tpm_ssdt(GArray *table_data, GArray *linker)
1235 {
1236     void *tpm_ptr;
1237 
1238     tpm_ptr = acpi_data_push(table_data, sizeof(ssdt_tpm_aml));
1239     memcpy(tpm_ptr, ssdt_tpm_aml, sizeof(ssdt_tpm_aml));
1240 }
1241 
1242 typedef enum {
1243     MEM_AFFINITY_NOFLAGS      = 0,
1244     MEM_AFFINITY_ENABLED      = (1 << 0),
1245     MEM_AFFINITY_HOTPLUGGABLE = (1 << 1),
1246     MEM_AFFINITY_NON_VOLATILE = (1 << 2),
1247 } MemoryAffinityFlags;
1248 
1249 static void
1250 acpi_build_srat_memory(AcpiSratMemoryAffinity *numamem, uint64_t base,
1251                        uint64_t len, int node, MemoryAffinityFlags flags)
1252 {
1253     numamem->type = ACPI_SRAT_MEMORY;
1254     numamem->length = sizeof(*numamem);
1255     memset(numamem->proximity, 0, 4);
1256     numamem->proximity[0] = node;
1257     numamem->flags = cpu_to_le32(flags);
1258     numamem->base_addr = cpu_to_le64(base);
1259     numamem->range_length = cpu_to_le64(len);
1260 }
1261 
1262 static void
1263 build_srat(GArray *table_data, GArray *linker,
1264            AcpiCpuInfo *cpu, PcGuestInfo *guest_info)
1265 {
1266     AcpiSystemResourceAffinityTable *srat;
1267     AcpiSratProcessorAffinity *core;
1268     AcpiSratMemoryAffinity *numamem;
1269 
1270     int i;
1271     uint64_t curnode;
1272     int srat_start, numa_start, slots;
1273     uint64_t mem_len, mem_base, next_base;
1274     PCMachineState *pcms = PC_MACHINE(qdev_get_machine());
1275     ram_addr_t hotplugabble_address_space_size =
1276         object_property_get_int(OBJECT(pcms), PC_MACHINE_MEMHP_REGION_SIZE,
1277                                 NULL);
1278 
1279     srat_start = table_data->len;
1280 
1281     srat = acpi_data_push(table_data, sizeof *srat);
1282     srat->reserved1 = cpu_to_le32(1);
1283     core = (void *)(srat + 1);
1284 
1285     for (i = 0; i < guest_info->apic_id_limit; ++i) {
1286         core = acpi_data_push(table_data, sizeof *core);
1287         core->type = ACPI_SRAT_PROCESSOR;
1288         core->length = sizeof(*core);
1289         core->local_apic_id = i;
1290         curnode = guest_info->node_cpu[i];
1291         core->proximity_lo = curnode;
1292         memset(core->proximity_hi, 0, 3);
1293         core->local_sapic_eid = 0;
1294         if (test_bit(i, cpu->found_cpus)) {
1295             core->flags = cpu_to_le32(1);
1296         } else {
1297             core->flags = cpu_to_le32(0);
1298         }
1299     }
1300 
1301 
1302     /* the memory map is a bit tricky, it contains at least one hole
1303      * from 640k-1M and possibly another one from 3.5G-4G.
1304      */
1305     next_base = 0;
1306     numa_start = table_data->len;
1307 
1308     numamem = acpi_data_push(table_data, sizeof *numamem);
1309     acpi_build_srat_memory(numamem, 0, 640*1024, 0, MEM_AFFINITY_ENABLED);
1310     next_base = 1024 * 1024;
1311     for (i = 1; i < guest_info->numa_nodes + 1; ++i) {
1312         mem_base = next_base;
1313         mem_len = guest_info->node_mem[i - 1];
1314         if (i == 1) {
1315             mem_len -= 1024 * 1024;
1316         }
1317         next_base = mem_base + mem_len;
1318 
1319         /* Cut out the ACPI_PCI hole */
1320         if (mem_base <= guest_info->ram_size_below_4g &&
1321             next_base > guest_info->ram_size_below_4g) {
1322             mem_len -= next_base - guest_info->ram_size_below_4g;
1323             if (mem_len > 0) {
1324                 numamem = acpi_data_push(table_data, sizeof *numamem);
1325                 acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1,
1326                                        MEM_AFFINITY_ENABLED);
1327             }
1328             mem_base = 1ULL << 32;
1329             mem_len = next_base - guest_info->ram_size_below_4g;
1330             next_base += (1ULL << 32) - guest_info->ram_size_below_4g;
1331         }
1332         numamem = acpi_data_push(table_data, sizeof *numamem);
1333         acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1,
1334                                MEM_AFFINITY_ENABLED);
1335     }
1336     slots = (table_data->len - numa_start) / sizeof *numamem;
1337     for (; slots < guest_info->numa_nodes + 2; slots++) {
1338         numamem = acpi_data_push(table_data, sizeof *numamem);
1339         acpi_build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS);
1340     }
1341 
1342     /*
1343      * Entry is required for Windows to enable memory hotplug in OS.
1344      * Memory devices may override proximity set by this entry,
1345      * providing _PXM method if necessary.
1346      */
1347     if (hotplugabble_address_space_size) {
1348         numamem = acpi_data_push(table_data, sizeof *numamem);
1349         acpi_build_srat_memory(numamem, pcms->hotplug_memory_base,
1350                                hotplugabble_address_space_size, 0,
1351                                MEM_AFFINITY_HOTPLUGGABLE |
1352                                MEM_AFFINITY_ENABLED);
1353     }
1354 
1355     build_header(linker, table_data,
1356                  (void *)(table_data->data + srat_start),
1357                  "SRAT",
1358                  table_data->len - srat_start, 1);
1359 }
1360 
1361 static void
1362 build_mcfg_q35(GArray *table_data, GArray *linker, AcpiMcfgInfo *info)
1363 {
1364     AcpiTableMcfg *mcfg;
1365     const char *sig;
1366     int len = sizeof(*mcfg) + 1 * sizeof(mcfg->allocation[0]);
1367 
1368     mcfg = acpi_data_push(table_data, len);
1369     mcfg->allocation[0].address = cpu_to_le64(info->mcfg_base);
1370     /* Only a single allocation so no need to play with segments */
1371     mcfg->allocation[0].pci_segment = cpu_to_le16(0);
1372     mcfg->allocation[0].start_bus_number = 0;
1373     mcfg->allocation[0].end_bus_number = PCIE_MMCFG_BUS(info->mcfg_size - 1);
1374 
1375     /* MCFG is used for ECAM which can be enabled or disabled by guest.
1376      * To avoid table size changes (which create migration issues),
1377      * always create the table even if there are no allocations,
1378      * but set the signature to a reserved value in this case.
1379      * ACPI spec requires OSPMs to ignore such tables.
1380      */
1381     if (info->mcfg_base == PCIE_BASE_ADDR_UNMAPPED) {
1382         /* Reserved signature: ignored by OSPM */
1383         sig = "QEMU";
1384     } else {
1385         sig = "MCFG";
1386     }
1387     build_header(linker, table_data, (void *)mcfg, sig, len, 1);
1388 }
1389 
1390 static void
1391 build_dsdt(GArray *table_data, GArray *linker, AcpiMiscInfo *misc)
1392 {
1393     AcpiTableHeader *dsdt;
1394 
1395     assert(misc->dsdt_code && misc->dsdt_size);
1396 
1397     dsdt = acpi_data_push(table_data, misc->dsdt_size);
1398     memcpy(dsdt, misc->dsdt_code, misc->dsdt_size);
1399 
1400     memset(dsdt, 0, sizeof *dsdt);
1401     build_header(linker, table_data, dsdt, "DSDT",
1402                  misc->dsdt_size, 1);
1403 }
1404 
1405 /* Build final rsdt table */
1406 static void
1407 build_rsdt(GArray *table_data, GArray *linker, GArray *table_offsets)
1408 {
1409     AcpiRsdtDescriptorRev1 *rsdt;
1410     size_t rsdt_len;
1411     int i;
1412 
1413     rsdt_len = sizeof(*rsdt) + sizeof(uint32_t) * table_offsets->len;
1414     rsdt = acpi_data_push(table_data, rsdt_len);
1415     memcpy(rsdt->table_offset_entry, table_offsets->data,
1416            sizeof(uint32_t) * table_offsets->len);
1417     for (i = 0; i < table_offsets->len; ++i) {
1418         /* rsdt->table_offset_entry to be filled by Guest linker */
1419         bios_linker_loader_add_pointer(linker,
1420                                        ACPI_BUILD_TABLE_FILE,
1421                                        ACPI_BUILD_TABLE_FILE,
1422                                        table_data, &rsdt->table_offset_entry[i],
1423                                        sizeof(uint32_t));
1424     }
1425     build_header(linker, table_data,
1426                  (void *)rsdt, "RSDT", rsdt_len, 1);
1427 }
1428 
1429 static GArray *
1430 build_rsdp(GArray *rsdp_table, GArray *linker, unsigned rsdt)
1431 {
1432     AcpiRsdpDescriptor *rsdp = acpi_data_push(rsdp_table, sizeof *rsdp);
1433 
1434     bios_linker_loader_alloc(linker, ACPI_BUILD_RSDP_FILE, 16,
1435                              true /* fseg memory */);
1436 
1437     memcpy(&rsdp->signature, "RSD PTR ", 8);
1438     memcpy(rsdp->oem_id, ACPI_BUILD_APPNAME6, 6);
1439     rsdp->rsdt_physical_address = cpu_to_le32(rsdt);
1440     /* Address to be filled by Guest linker */
1441     bios_linker_loader_add_pointer(linker, ACPI_BUILD_RSDP_FILE,
1442                                    ACPI_BUILD_TABLE_FILE,
1443                                    rsdp_table, &rsdp->rsdt_physical_address,
1444                                    sizeof rsdp->rsdt_physical_address);
1445     rsdp->checksum = 0;
1446     /* Checksum to be filled by Guest linker */
1447     bios_linker_loader_add_checksum(linker, ACPI_BUILD_RSDP_FILE,
1448                                     rsdp, rsdp, sizeof *rsdp, &rsdp->checksum);
1449 
1450     return rsdp_table;
1451 }
1452 
1453 typedef
1454 struct AcpiBuildTables {
1455     GArray *table_data;
1456     GArray *rsdp;
1457     GArray *linker;
1458 } AcpiBuildTables;
1459 
1460 static inline void acpi_build_tables_init(AcpiBuildTables *tables)
1461 {
1462     tables->rsdp = g_array_new(false, true /* clear */, 1);
1463     tables->table_data = g_array_new(false, true /* clear */, 1);
1464     tables->linker = bios_linker_loader_init();
1465 }
1466 
1467 static inline void acpi_build_tables_cleanup(AcpiBuildTables *tables, bool mfre)
1468 {
1469     void *linker_data = bios_linker_loader_cleanup(tables->linker);
1470     if (mfre) {
1471         g_free(linker_data);
1472     }
1473     g_array_free(tables->rsdp, mfre);
1474     g_array_free(tables->table_data, mfre);
1475 }
1476 
1477 typedef
1478 struct AcpiBuildState {
1479     /* Copy of table in RAM (for patching). */
1480     uint8_t *table_ram;
1481     uint32_t table_size;
1482     /* Is table patched? */
1483     uint8_t patched;
1484     PcGuestInfo *guest_info;
1485 } AcpiBuildState;
1486 
1487 static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
1488 {
1489     Object *pci_host;
1490     QObject *o;
1491     bool ambiguous;
1492 
1493     pci_host = object_resolve_path_type("", TYPE_PCI_HOST_BRIDGE, &ambiguous);
1494     g_assert(!ambiguous);
1495     g_assert(pci_host);
1496 
1497     o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_BASE, NULL);
1498     if (!o) {
1499         return false;
1500     }
1501     mcfg->mcfg_base = qint_get_int(qobject_to_qint(o));
1502     qobject_decref(o);
1503 
1504     o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_SIZE, NULL);
1505     assert(o);
1506     mcfg->mcfg_size = qint_get_int(qobject_to_qint(o));
1507     qobject_decref(o);
1508     return true;
1509 }
1510 
1511 static
1512 void acpi_build(PcGuestInfo *guest_info, AcpiBuildTables *tables)
1513 {
1514     GArray *table_offsets;
1515     unsigned facs, ssdt, dsdt, rsdt;
1516     AcpiCpuInfo cpu;
1517     AcpiPmInfo pm;
1518     AcpiMiscInfo misc;
1519     AcpiMcfgInfo mcfg;
1520     PcPciInfo pci;
1521     uint8_t *u;
1522     size_t aml_len = 0;
1523 
1524     acpi_get_cpu_info(&cpu);
1525     acpi_get_pm_info(&pm);
1526     acpi_get_dsdt(&misc);
1527     acpi_get_misc_info(&misc);
1528     acpi_get_pci_info(&pci);
1529 
1530     table_offsets = g_array_new(false, true /* clear */,
1531                                         sizeof(uint32_t));
1532     ACPI_BUILD_DPRINTF(3, "init ACPI tables\n");
1533 
1534     bios_linker_loader_alloc(tables->linker, ACPI_BUILD_TABLE_FILE,
1535                              64 /* Ensure FACS is aligned */,
1536                              false /* high memory */);
1537 
1538     /*
1539      * FACS is pointed to by FADT.
1540      * We place it first since it's the only table that has alignment
1541      * requirements.
1542      */
1543     facs = tables->table_data->len;
1544     build_facs(tables->table_data, tables->linker, guest_info);
1545 
1546     /* DSDT is pointed to by FADT */
1547     dsdt = tables->table_data->len;
1548     build_dsdt(tables->table_data, tables->linker, &misc);
1549 
1550     /* Count the size of the DSDT and SSDT, we will need it for legacy
1551      * sizing of ACPI tables.
1552      */
1553     aml_len += tables->table_data->len - dsdt;
1554 
1555     /* ACPI tables pointed to by RSDT */
1556     acpi_add_table(table_offsets, tables->table_data);
1557     build_fadt(tables->table_data, tables->linker, &pm, facs, dsdt);
1558 
1559     ssdt = tables->table_data->len;
1560     acpi_add_table(table_offsets, tables->table_data);
1561     build_ssdt(tables->table_data, tables->linker, &cpu, &pm, &misc, &pci,
1562                guest_info);
1563     aml_len += tables->table_data->len - ssdt;
1564 
1565     acpi_add_table(table_offsets, tables->table_data);
1566     build_madt(tables->table_data, tables->linker, &cpu, guest_info);
1567 
1568     if (misc.has_hpet) {
1569         acpi_add_table(table_offsets, tables->table_data);
1570         build_hpet(tables->table_data, tables->linker);
1571     }
1572     if (misc.has_tpm) {
1573         acpi_add_table(table_offsets, tables->table_data);
1574         build_tpm_tcpa(tables->table_data, tables->linker);
1575 
1576         acpi_add_table(table_offsets, tables->table_data);
1577         build_tpm_ssdt(tables->table_data, tables->linker);
1578     }
1579     if (guest_info->numa_nodes) {
1580         acpi_add_table(table_offsets, tables->table_data);
1581         build_srat(tables->table_data, tables->linker, &cpu, guest_info);
1582     }
1583     if (acpi_get_mcfg(&mcfg)) {
1584         acpi_add_table(table_offsets, tables->table_data);
1585         build_mcfg_q35(tables->table_data, tables->linker, &mcfg);
1586     }
1587 
1588     /* Add tables supplied by user (if any) */
1589     for (u = acpi_table_first(); u; u = acpi_table_next(u)) {
1590         unsigned len = acpi_table_len(u);
1591 
1592         acpi_add_table(table_offsets, tables->table_data);
1593         g_array_append_vals(tables->table_data, u, len);
1594     }
1595 
1596     /* RSDT is pointed to by RSDP */
1597     rsdt = tables->table_data->len;
1598     build_rsdt(tables->table_data, tables->linker, table_offsets);
1599 
1600     /* RSDP is in FSEG memory, so allocate it separately */
1601     build_rsdp(tables->rsdp, tables->linker, rsdt);
1602 
1603     /* We'll expose it all to Guest so we want to reduce
1604      * chance of size changes.
1605      * RSDP is small so it's easy to keep it immutable, no need to
1606      * bother with alignment.
1607      *
1608      * We used to align the tables to 4k, but of course this would
1609      * too simple to be enough.  4k turned out to be too small an
1610      * alignment very soon, and in fact it is almost impossible to
1611      * keep the table size stable for all (max_cpus, max_memory_slots)
1612      * combinations.  So the table size is always 64k for pc-i440fx-2.1
1613      * and we give an error if the table grows beyond that limit.
1614      *
1615      * We still have the problem of migrating from "-M pc-i440fx-2.0".  For
1616      * that, we exploit the fact that QEMU 2.1 generates _smaller_ tables
1617      * than 2.0 and we can always pad the smaller tables with zeros.  We can
1618      * then use the exact size of the 2.0 tables.
1619      *
1620      * All this is for PIIX4, since QEMU 2.0 didn't support Q35 migration.
1621      */
1622     if (guest_info->legacy_acpi_table_size) {
1623         /* Subtracting aml_len gives the size of fixed tables.  Then add the
1624          * size of the PIIX4 DSDT/SSDT in QEMU 2.0.
1625          */
1626         int legacy_aml_len =
1627             guest_info->legacy_acpi_table_size +
1628             ACPI_BUILD_LEGACY_CPU_AML_SIZE * max_cpus;
1629         int legacy_table_size =
1630             ROUND_UP(tables->table_data->len - aml_len + legacy_aml_len,
1631                      ACPI_BUILD_ALIGN_SIZE);
1632         if (tables->table_data->len > legacy_table_size) {
1633             /* Should happen only with PCI bridges and -M pc-i440fx-2.0.  */
1634             error_report("Warning: migration may not work.");
1635         }
1636         g_array_set_size(tables->table_data, legacy_table_size);
1637     } else {
1638         /* Make sure we have a buffer in case we need to resize the tables. */
1639         if (tables->table_data->len > ACPI_BUILD_TABLE_SIZE / 2) {
1640             /* As of QEMU 2.1, this fires with 160 VCPUs and 255 memory slots.  */
1641             error_report("Warning: ACPI tables are larger than 64k.");
1642             error_report("Warning: migration may not work.");
1643             error_report("Warning: please remove CPUs, NUMA nodes, "
1644                          "memory slots or PCI bridges.");
1645         }
1646         acpi_align_size(tables->table_data, ACPI_BUILD_TABLE_SIZE);
1647     }
1648 
1649     acpi_align_size(tables->linker, ACPI_BUILD_ALIGN_SIZE);
1650 
1651     /* Cleanup memory that's no longer used. */
1652     g_array_free(table_offsets, true);
1653 }
1654 
1655 static void acpi_build_update(void *build_opaque, uint32_t offset)
1656 {
1657     AcpiBuildState *build_state = build_opaque;
1658     AcpiBuildTables tables;
1659 
1660     /* No state to update or already patched? Nothing to do. */
1661     if (!build_state || build_state->patched) {
1662         return;
1663     }
1664     build_state->patched = 1;
1665 
1666     acpi_build_tables_init(&tables);
1667 
1668     acpi_build(build_state->guest_info, &tables);
1669 
1670     assert(acpi_data_len(tables.table_data) == build_state->table_size);
1671     memcpy(build_state->table_ram, tables.table_data->data,
1672            build_state->table_size);
1673 
1674     acpi_build_tables_cleanup(&tables, true);
1675 }
1676 
1677 static void acpi_build_reset(void *build_opaque)
1678 {
1679     AcpiBuildState *build_state = build_opaque;
1680     build_state->patched = 0;
1681 }
1682 
1683 static void *acpi_add_rom_blob(AcpiBuildState *build_state, GArray *blob,
1684                                const char *name)
1685 {
1686     return rom_add_blob(name, blob->data, acpi_data_len(blob), -1, name,
1687                         acpi_build_update, build_state);
1688 }
1689 
1690 static const VMStateDescription vmstate_acpi_build = {
1691     .name = "acpi_build",
1692     .version_id = 1,
1693     .minimum_version_id = 1,
1694     .fields = (VMStateField[]) {
1695         VMSTATE_UINT8(patched, AcpiBuildState),
1696         VMSTATE_END_OF_LIST()
1697     },
1698 };
1699 
1700 void acpi_setup(PcGuestInfo *guest_info)
1701 {
1702     AcpiBuildTables tables;
1703     AcpiBuildState *build_state;
1704 
1705     if (!guest_info->fw_cfg) {
1706         ACPI_BUILD_DPRINTF(3, "No fw cfg. Bailing out.\n");
1707         return;
1708     }
1709 
1710     if (!guest_info->has_acpi_build) {
1711         ACPI_BUILD_DPRINTF(3, "ACPI build disabled. Bailing out.\n");
1712         return;
1713     }
1714 
1715     if (!acpi_enabled) {
1716         ACPI_BUILD_DPRINTF(3, "ACPI disabled. Bailing out.\n");
1717         return;
1718     }
1719 
1720     build_state = g_malloc0(sizeof *build_state);
1721 
1722     build_state->guest_info = guest_info;
1723 
1724     acpi_set_pci_info();
1725 
1726     acpi_build_tables_init(&tables);
1727     acpi_build(build_state->guest_info, &tables);
1728 
1729     /* Now expose it all to Guest */
1730     build_state->table_ram = acpi_add_rom_blob(build_state, tables.table_data,
1731                                                ACPI_BUILD_TABLE_FILE);
1732     build_state->table_size = acpi_data_len(tables.table_data);
1733 
1734     acpi_add_rom_blob(NULL, tables.linker, "etc/table-loader");
1735 
1736     /*
1737      * RSDP is small so it's easy to keep it immutable, no need to
1738      * bother with ROM blobs.
1739      */
1740     fw_cfg_add_file(guest_info->fw_cfg, ACPI_BUILD_RSDP_FILE,
1741                     tables.rsdp->data, acpi_data_len(tables.rsdp));
1742 
1743     qemu_register_reset(acpi_build_reset, build_state);
1744     acpi_build_reset(build_state);
1745     vmstate_register(NULL, 0, &vmstate_acpi_build, build_state);
1746 
1747     /* Cleanup tables but don't free the memory: we track it
1748      * in build_state.
1749      */
1750     acpi_build_tables_cleanup(&tables, false);
1751 }
1752