xref: /openbmc/qemu/hw/i386/acpi-build.c (revision d6032e06)
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/range.h"
29 #include "hw/pci/pci.h"
30 #include "qom/cpu.h"
31 #include "hw/i386/pc.h"
32 #include "target-i386/cpu.h"
33 #include "hw/timer/hpet.h"
34 #include "hw/i386/acpi-defs.h"
35 #include "hw/acpi/acpi.h"
36 #include "hw/nvram/fw_cfg.h"
37 #include "bios-linker-loader.h"
38 #include "hw/loader.h"
39 #include "hw/isa/isa.h"
40 
41 /* Supported chipsets: */
42 #include "hw/acpi/piix4.h"
43 #include "hw/acpi/pcihp.h"
44 #include "hw/i386/ich9.h"
45 #include "hw/pci/pci_bus.h"
46 #include "hw/pci-host/q35.h"
47 
48 #include "hw/i386/q35-acpi-dsdt.hex"
49 #include "hw/i386/acpi-dsdt.hex"
50 
51 #include "qapi/qmp/qint.h"
52 #include "qom/qom-qobject.h"
53 
54 typedef struct AcpiCpuInfo {
55     DECLARE_BITMAP(found_cpus, MAX_CPUMASK_BITS + 1);
56 } AcpiCpuInfo;
57 
58 typedef struct AcpiMcfgInfo {
59     uint64_t mcfg_base;
60     uint32_t mcfg_size;
61 } AcpiMcfgInfo;
62 
63 typedef struct AcpiPmInfo {
64     bool s3_disabled;
65     bool s4_disabled;
66     uint8_t s4_val;
67     uint16_t sci_int;
68     uint8_t acpi_enable_cmd;
69     uint8_t acpi_disable_cmd;
70     uint32_t gpe0_blk;
71     uint32_t gpe0_blk_len;
72     uint32_t io_base;
73 } AcpiPmInfo;
74 
75 typedef struct AcpiMiscInfo {
76     bool has_hpet;
77     DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX);
78     const unsigned char *dsdt_code;
79     unsigned dsdt_size;
80     uint16_t pvpanic_port;
81 } AcpiMiscInfo;
82 
83 typedef struct AcpiBuildPciBusHotplugState {
84     GArray *device_table;
85     GArray *notify_table;
86     struct AcpiBuildPciBusHotplugState *parent;
87 } AcpiBuildPciBusHotplugState;
88 
89 static void acpi_get_dsdt(AcpiMiscInfo *info)
90 {
91     uint16_t *applesmc_sta;
92     Object *piix = piix4_pm_find();
93     Object *lpc = ich9_lpc_find();
94     assert(!!piix != !!lpc);
95 
96     if (piix) {
97         info->dsdt_code = AcpiDsdtAmlCode;
98         info->dsdt_size = sizeof AcpiDsdtAmlCode;
99         applesmc_sta = piix_dsdt_applesmc_sta;
100     }
101     if (lpc) {
102         info->dsdt_code = Q35AcpiDsdtAmlCode;
103         info->dsdt_size = sizeof Q35AcpiDsdtAmlCode;
104         applesmc_sta = q35_dsdt_applesmc_sta;
105     }
106 
107     /* Patch in appropriate value for AppleSMC _STA */
108     *(uint8_t *)(info->dsdt_code + *applesmc_sta) =
109         applesmc_find() ? 0x0b : 0x00;
110 }
111 
112 static
113 int acpi_add_cpu_info(Object *o, void *opaque)
114 {
115     AcpiCpuInfo *cpu = opaque;
116     uint64_t apic_id;
117 
118     if (object_dynamic_cast(o, TYPE_CPU)) {
119         apic_id = object_property_get_int(o, "apic-id", NULL);
120         assert(apic_id <= MAX_CPUMASK_BITS);
121 
122         set_bit(apic_id, cpu->found_cpus);
123     }
124 
125     object_child_foreach(o, acpi_add_cpu_info, opaque);
126     return 0;
127 }
128 
129 static void acpi_get_cpu_info(AcpiCpuInfo *cpu)
130 {
131     Object *root = object_get_root();
132 
133     memset(cpu->found_cpus, 0, sizeof cpu->found_cpus);
134     object_child_foreach(root, acpi_add_cpu_info, cpu);
135 }
136 
137 static void acpi_get_pm_info(AcpiPmInfo *pm)
138 {
139     Object *piix = piix4_pm_find();
140     Object *lpc = ich9_lpc_find();
141     Object *obj = NULL;
142     QObject *o;
143 
144     if (piix) {
145         obj = piix;
146     }
147     if (lpc) {
148         obj = lpc;
149     }
150     assert(obj);
151 
152     /* Fill in optional s3/s4 related properties */
153     o = object_property_get_qobject(obj, ACPI_PM_PROP_S3_DISABLED, NULL);
154     if (o) {
155         pm->s3_disabled = qint_get_int(qobject_to_qint(o));
156     } else {
157         pm->s3_disabled = false;
158     }
159     o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL);
160     if (o) {
161         pm->s4_disabled = qint_get_int(qobject_to_qint(o));
162     } else {
163         pm->s4_disabled = false;
164     }
165     o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL);
166     if (o) {
167         pm->s4_val = qint_get_int(qobject_to_qint(o));
168     } else {
169         pm->s4_val = false;
170     }
171 
172     /* Fill in mandatory properties */
173     pm->sci_int = object_property_get_int(obj, ACPI_PM_PROP_SCI_INT, NULL);
174 
175     pm->acpi_enable_cmd = object_property_get_int(obj,
176                                                   ACPI_PM_PROP_ACPI_ENABLE_CMD,
177                                                   NULL);
178     pm->acpi_disable_cmd = object_property_get_int(obj,
179                                                   ACPI_PM_PROP_ACPI_DISABLE_CMD,
180                                                   NULL);
181     pm->io_base = object_property_get_int(obj, ACPI_PM_PROP_PM_IO_BASE,
182                                           NULL);
183     pm->gpe0_blk = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK,
184                                            NULL);
185     pm->gpe0_blk_len = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK_LEN,
186                                                NULL);
187 }
188 
189 static void acpi_get_misc_info(AcpiMiscInfo *info)
190 {
191     info->has_hpet = hpet_find();
192     info->pvpanic_port = pvpanic_port();
193 }
194 
195 static void acpi_get_pci_info(PcPciInfo *info)
196 {
197     Object *pci_host;
198     bool ambiguous;
199 
200     pci_host = object_resolve_path_type("", TYPE_PCI_HOST_BRIDGE, &ambiguous);
201     g_assert(!ambiguous);
202     g_assert(pci_host);
203 
204     info->w32.begin = object_property_get_int(pci_host,
205                                               PCI_HOST_PROP_PCI_HOLE_START,
206                                               NULL);
207     info->w32.end = object_property_get_int(pci_host,
208                                             PCI_HOST_PROP_PCI_HOLE_END,
209                                             NULL);
210     info->w64.begin = object_property_get_int(pci_host,
211                                               PCI_HOST_PROP_PCI_HOLE64_START,
212                                               NULL);
213     info->w64.end = object_property_get_int(pci_host,
214                                             PCI_HOST_PROP_PCI_HOLE64_END,
215                                             NULL);
216 }
217 
218 #define ACPI_BUILD_APPNAME  "Bochs"
219 #define ACPI_BUILD_APPNAME6 "BOCHS "
220 #define ACPI_BUILD_APPNAME4 "BXPC"
221 
222 #define ACPI_BUILD_DPRINTF(level, fmt, ...) do {} while (0)
223 
224 #define ACPI_BUILD_TABLE_FILE "etc/acpi/tables"
225 #define ACPI_BUILD_RSDP_FILE "etc/acpi/rsdp"
226 
227 static void
228 build_header(GArray *linker, GArray *table_data,
229              AcpiTableHeader *h, uint32_t sig, int len, uint8_t rev)
230 {
231     h->signature = cpu_to_le32(sig);
232     h->length = cpu_to_le32(len);
233     h->revision = rev;
234     memcpy(h->oem_id, ACPI_BUILD_APPNAME6, 6);
235     memcpy(h->oem_table_id, ACPI_BUILD_APPNAME4, 4);
236     memcpy(h->oem_table_id + 4, (void *)&sig, 4);
237     h->oem_revision = cpu_to_le32(1);
238     memcpy(h->asl_compiler_id, ACPI_BUILD_APPNAME4, 4);
239     h->asl_compiler_revision = cpu_to_le32(1);
240     h->checksum = 0;
241     /* Checksum to be filled in by Guest linker */
242     bios_linker_loader_add_checksum(linker, ACPI_BUILD_TABLE_FILE,
243                                     table_data->data, h, len, &h->checksum);
244 }
245 
246 static inline GArray *build_alloc_array(void)
247 {
248         return g_array_new(false, true /* clear */, 1);
249 }
250 
251 static inline void build_free_array(GArray *array)
252 {
253         g_array_free(array, true);
254 }
255 
256 static inline void build_prepend_byte(GArray *array, uint8_t val)
257 {
258     g_array_prepend_val(array, val);
259 }
260 
261 static inline void build_append_byte(GArray *array, uint8_t val)
262 {
263     g_array_append_val(array, val);
264 }
265 
266 static inline void build_append_array(GArray *array, GArray *val)
267 {
268     g_array_append_vals(array, val->data, val->len);
269 }
270 
271 static void GCC_FMT_ATTR(2, 3)
272 build_append_nameseg(GArray *array, const char *format, ...)
273 {
274     /* It would be nicer to use g_string_vprintf but it's only there in 2.22 */
275     char s[] = "XXXX";
276     int len;
277     va_list args;
278 
279     va_start(args, format);
280     len = vsnprintf(s, sizeof s, format, args);
281     va_end(args);
282 
283     assert(len == 4);
284     g_array_append_vals(array, s, len);
285 }
286 
287 /* 5.4 Definition Block Encoding */
288 enum {
289     PACKAGE_LENGTH_1BYTE_SHIFT = 6, /* Up to 63 - use extra 2 bits. */
290     PACKAGE_LENGTH_2BYTE_SHIFT = 4,
291     PACKAGE_LENGTH_3BYTE_SHIFT = 12,
292     PACKAGE_LENGTH_4BYTE_SHIFT = 20,
293 };
294 
295 static void build_prepend_package_length(GArray *package, unsigned min_bytes)
296 {
297     uint8_t byte;
298     unsigned length = package->len;
299     unsigned length_bytes;
300 
301     if (length + 1 < (1 << PACKAGE_LENGTH_1BYTE_SHIFT)) {
302         length_bytes = 1;
303     } else if (length + 2 < (1 << PACKAGE_LENGTH_3BYTE_SHIFT)) {
304         length_bytes = 2;
305     } else if (length + 3 < (1 << PACKAGE_LENGTH_4BYTE_SHIFT)) {
306         length_bytes = 3;
307     } else {
308         length_bytes = 4;
309     }
310 
311     /* Force length to at least min_bytes.
312      * This wastes memory but that's how bios did it.
313      */
314     length_bytes = MAX(length_bytes, min_bytes);
315 
316     /* PkgLength is the length of the inclusive length of the data. */
317     length += length_bytes;
318 
319     switch (length_bytes) {
320     case 1:
321         byte = length;
322         build_prepend_byte(package, byte);
323         return;
324     case 4:
325         byte = length >> PACKAGE_LENGTH_4BYTE_SHIFT;
326         build_prepend_byte(package, byte);
327         length &= (1 << PACKAGE_LENGTH_4BYTE_SHIFT) - 1;
328         /* fall through */
329     case 3:
330         byte = length >> PACKAGE_LENGTH_3BYTE_SHIFT;
331         build_prepend_byte(package, byte);
332         length &= (1 << PACKAGE_LENGTH_3BYTE_SHIFT) - 1;
333         /* fall through */
334     case 2:
335         byte = length >> PACKAGE_LENGTH_2BYTE_SHIFT;
336         build_prepend_byte(package, byte);
337         length &= (1 << PACKAGE_LENGTH_2BYTE_SHIFT) - 1;
338         /* fall through */
339     }
340     /*
341      * Most significant two bits of byte zero indicate how many following bytes
342      * are in PkgLength encoding.
343      */
344     byte = ((length_bytes - 1) << PACKAGE_LENGTH_1BYTE_SHIFT) | length;
345     build_prepend_byte(package, byte);
346 }
347 
348 static void build_package(GArray *package, uint8_t op, unsigned min_bytes)
349 {
350     build_prepend_package_length(package, min_bytes);
351     build_prepend_byte(package, op);
352 }
353 
354 static void build_extop_package(GArray *package, uint8_t op)
355 {
356     build_package(package, op, 1);
357     build_prepend_byte(package, 0x5B); /* ExtOpPrefix */
358 }
359 
360 static void build_append_value(GArray *table, uint32_t value, int size)
361 {
362     uint8_t prefix;
363     int i;
364 
365     switch (size) {
366     case 1:
367         prefix = 0x0A; /* BytePrefix */
368         break;
369     case 2:
370         prefix = 0x0B; /* WordPrefix */
371         break;
372     case 4:
373         prefix = 0x0C; /* DWordPrefix */
374         break;
375     default:
376         assert(0);
377         return;
378     }
379     build_append_byte(table, prefix);
380     for (i = 0; i < size; ++i) {
381         build_append_byte(table, value & 0xFF);
382         value = value >> 8;
383     }
384 }
385 
386 static void build_append_int(GArray *table, uint32_t value)
387 {
388     if (value == 0x00) {
389         build_append_byte(table, 0x00); /* ZeroOp */
390     } else if (value == 0x01) {
391         build_append_byte(table, 0x01); /* OneOp */
392     } else if (value <= 0xFF) {
393         build_append_value(table, value, 1);
394     } else if (value <= 0xFFFFF) {
395         build_append_value(table, value, 2);
396     } else {
397         build_append_value(table, value, 4);
398     }
399 }
400 
401 static GArray *build_alloc_method(const char *name, uint8_t arg_count)
402 {
403     GArray *method = build_alloc_array();
404 
405     build_append_nameseg(method, "%s", name);
406     build_append_byte(method, arg_count); /* MethodFlags: ArgCount */
407 
408     return method;
409 }
410 
411 static void build_append_and_cleanup_method(GArray *device, GArray *method)
412 {
413     uint8_t op = 0x14; /* MethodOp */
414 
415     build_package(method, op, 0);
416 
417     build_append_array(device, method);
418     build_free_array(method);
419 }
420 
421 static void build_append_notify_target_ifequal(GArray *method,
422                                                GArray *target_name,
423                                                uint32_t value, int size)
424 {
425     GArray *notify = build_alloc_array();
426     uint8_t op = 0xA0; /* IfOp */
427 
428     build_append_byte(notify, 0x93); /* LEqualOp */
429     build_append_byte(notify, 0x68); /* Arg0Op */
430     build_append_value(notify, value, size);
431     build_append_byte(notify, 0x86); /* NotifyOp */
432     build_append_array(notify, target_name);
433     build_append_byte(notify, 0x69); /* Arg1Op */
434 
435     /* Pack it up */
436     build_package(notify, op, 1);
437 
438     build_append_array(method, notify);
439 
440     build_free_array(notify);
441 }
442 
443 /* End here */
444 #define ACPI_PORT_SMI_CMD           0x00b2 /* TODO: this is APM_CNT_IOPORT */
445 
446 static inline void *acpi_data_push(GArray *table_data, unsigned size)
447 {
448     unsigned off = table_data->len;
449     g_array_set_size(table_data, off + size);
450     return table_data->data + off;
451 }
452 
453 static unsigned acpi_data_len(GArray *table)
454 {
455 #if GLIB_CHECK_VERSION(2, 22, 0)
456     assert(g_array_get_element_size(table) == 1);
457 #endif
458     return table->len;
459 }
460 
461 static void acpi_align_size(GArray *blob, unsigned align)
462 {
463     /* Align size to multiple of given size. This reduces the chance
464      * we need to change size in the future (breaking cross version migration).
465      */
466     g_array_set_size(blob, ROUND_UP(acpi_data_len(blob), align));
467 }
468 
469 /* Get pointer within table in a safe manner */
470 #define ACPI_BUILD_PTR(table, size, off, type) \
471     ((type *)(acpi_data_get_ptr(table, size, off, sizeof(type))))
472 
473 static inline void *acpi_data_get_ptr(uint8_t *table_data, unsigned table_size,
474                                       unsigned off, unsigned size)
475 {
476     assert(off + size > off);
477     assert(off + size <= table_size);
478     return table_data + off;
479 }
480 
481 static inline void acpi_add_table(GArray *table_offsets, GArray *table_data)
482 {
483     uint32_t offset = cpu_to_le32(table_data->len);
484     g_array_append_val(table_offsets, offset);
485 }
486 
487 /* FACS */
488 static void
489 build_facs(GArray *table_data, GArray *linker, PcGuestInfo *guest_info)
490 {
491     AcpiFacsDescriptorRev1 *facs = acpi_data_push(table_data, sizeof *facs);
492     facs->signature = cpu_to_le32(ACPI_FACS_SIGNATURE);
493     facs->length = cpu_to_le32(sizeof(*facs));
494 }
495 
496 /* Load chipset information in FADT */
497 static void fadt_setup(AcpiFadtDescriptorRev1 *fadt, AcpiPmInfo *pm)
498 {
499     fadt->model = 1;
500     fadt->reserved1 = 0;
501     fadt->sci_int = cpu_to_le16(pm->sci_int);
502     fadt->smi_cmd = cpu_to_le32(ACPI_PORT_SMI_CMD);
503     fadt->acpi_enable = pm->acpi_enable_cmd;
504     fadt->acpi_disable = pm->acpi_disable_cmd;
505     /* EVT, CNT, TMR offset matches hw/acpi/core.c */
506     fadt->pm1a_evt_blk = cpu_to_le32(pm->io_base);
507     fadt->pm1a_cnt_blk = cpu_to_le32(pm->io_base + 0x04);
508     fadt->pm_tmr_blk = cpu_to_le32(pm->io_base + 0x08);
509     fadt->gpe0_blk = cpu_to_le32(pm->gpe0_blk);
510     /* EVT, CNT, TMR length matches hw/acpi/core.c */
511     fadt->pm1_evt_len = 4;
512     fadt->pm1_cnt_len = 2;
513     fadt->pm_tmr_len = 4;
514     fadt->gpe0_blk_len = pm->gpe0_blk_len;
515     fadt->plvl2_lat = cpu_to_le16(0xfff); /* C2 state not supported */
516     fadt->plvl3_lat = cpu_to_le16(0xfff); /* C3 state not supported */
517     fadt->flags = cpu_to_le32((1 << ACPI_FADT_F_WBINVD) |
518                               (1 << ACPI_FADT_F_PROC_C1) |
519                               (1 << ACPI_FADT_F_SLP_BUTTON) |
520                               (1 << ACPI_FADT_F_RTC_S4));
521     fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_USE_PLATFORM_CLOCK);
522 }
523 
524 
525 /* FADT */
526 static void
527 build_fadt(GArray *table_data, GArray *linker, AcpiPmInfo *pm,
528            unsigned facs, unsigned dsdt)
529 {
530     AcpiFadtDescriptorRev1 *fadt = acpi_data_push(table_data, sizeof(*fadt));
531 
532     fadt->firmware_ctrl = cpu_to_le32(facs);
533     /* FACS address to be filled by Guest linker */
534     bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,
535                                    ACPI_BUILD_TABLE_FILE,
536                                    table_data, &fadt->firmware_ctrl,
537                                    sizeof fadt->firmware_ctrl);
538 
539     fadt->dsdt = cpu_to_le32(dsdt);
540     /* DSDT address to be filled by Guest linker */
541     bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,
542                                    ACPI_BUILD_TABLE_FILE,
543                                    table_data, &fadt->dsdt,
544                                    sizeof fadt->dsdt);
545 
546     fadt_setup(fadt, pm);
547 
548     build_header(linker, table_data,
549                  (void *)fadt, ACPI_FACP_SIGNATURE, sizeof(*fadt), 1);
550 }
551 
552 static void
553 build_madt(GArray *table_data, GArray *linker, AcpiCpuInfo *cpu,
554            PcGuestInfo *guest_info)
555 {
556     int madt_start = table_data->len;
557 
558     AcpiMultipleApicTable *madt;
559     AcpiMadtIoApic *io_apic;
560     AcpiMadtIntsrcovr *intsrcovr;
561     AcpiMadtLocalNmi *local_nmi;
562     int i;
563 
564     madt = acpi_data_push(table_data, sizeof *madt);
565     madt->local_apic_address = cpu_to_le32(APIC_DEFAULT_ADDRESS);
566     madt->flags = cpu_to_le32(1);
567 
568     for (i = 0; i < guest_info->apic_id_limit; i++) {
569         AcpiMadtProcessorApic *apic = acpi_data_push(table_data, sizeof *apic);
570         apic->type = ACPI_APIC_PROCESSOR;
571         apic->length = sizeof(*apic);
572         apic->processor_id = i;
573         apic->local_apic_id = i;
574         if (test_bit(i, cpu->found_cpus)) {
575             apic->flags = cpu_to_le32(1);
576         } else {
577             apic->flags = cpu_to_le32(0);
578         }
579     }
580     io_apic = acpi_data_push(table_data, sizeof *io_apic);
581     io_apic->type = ACPI_APIC_IO;
582     io_apic->length = sizeof(*io_apic);
583 #define ACPI_BUILD_IOAPIC_ID 0x0
584     io_apic->io_apic_id = ACPI_BUILD_IOAPIC_ID;
585     io_apic->address = cpu_to_le32(IO_APIC_DEFAULT_ADDRESS);
586     io_apic->interrupt = cpu_to_le32(0);
587 
588     if (guest_info->apic_xrupt_override) {
589         intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);
590         intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;
591         intsrcovr->length = sizeof(*intsrcovr);
592         intsrcovr->source = 0;
593         intsrcovr->gsi    = cpu_to_le32(2);
594         intsrcovr->flags  = cpu_to_le16(0); /* conforms to bus specifications */
595     }
596     for (i = 1; i < 16; i++) {
597 #define ACPI_BUILD_PCI_IRQS ((1<<5) | (1<<9) | (1<<10) | (1<<11))
598         if (!(ACPI_BUILD_PCI_IRQS & (1 << i))) {
599             /* No need for a INT source override structure. */
600             continue;
601         }
602         intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);
603         intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;
604         intsrcovr->length = sizeof(*intsrcovr);
605         intsrcovr->source = i;
606         intsrcovr->gsi    = cpu_to_le32(i);
607         intsrcovr->flags  = cpu_to_le16(0xd); /* active high, level triggered */
608     }
609 
610     local_nmi = acpi_data_push(table_data, sizeof *local_nmi);
611     local_nmi->type         = ACPI_APIC_LOCAL_NMI;
612     local_nmi->length       = sizeof(*local_nmi);
613     local_nmi->processor_id = 0xff; /* all processors */
614     local_nmi->flags        = cpu_to_le16(0);
615     local_nmi->lint         = 1; /* ACPI_LINT1 */
616 
617     build_header(linker, table_data,
618                  (void *)(table_data->data + madt_start), ACPI_APIC_SIGNATURE,
619                  table_data->len - madt_start, 1);
620 }
621 
622 /* Encode a hex value */
623 static inline char acpi_get_hex(uint32_t val)
624 {
625     val &= 0x0f;
626     return (val <= 9) ? ('0' + val) : ('A' + val - 10);
627 }
628 
629 #include "hw/i386/ssdt-proc.hex"
630 
631 /* 0x5B 0x83 ProcessorOp PkgLength NameString ProcID */
632 #define ACPI_PROC_OFFSET_CPUHEX (*ssdt_proc_name - *ssdt_proc_start + 2)
633 #define ACPI_PROC_OFFSET_CPUID1 (*ssdt_proc_name - *ssdt_proc_start + 4)
634 #define ACPI_PROC_OFFSET_CPUID2 (*ssdt_proc_id - *ssdt_proc_start)
635 #define ACPI_PROC_SIZEOF (*ssdt_proc_end - *ssdt_proc_start)
636 #define ACPI_PROC_AML (ssdp_proc_aml + *ssdt_proc_start)
637 
638 /* 0x5B 0x82 DeviceOp PkgLength NameString */
639 #define ACPI_PCIHP_OFFSET_HEX (*ssdt_pcihp_name - *ssdt_pcihp_start + 1)
640 #define ACPI_PCIHP_OFFSET_ID (*ssdt_pcihp_id - *ssdt_pcihp_start)
641 #define ACPI_PCIHP_OFFSET_ADR (*ssdt_pcihp_adr - *ssdt_pcihp_start)
642 #define ACPI_PCIHP_OFFSET_EJ0 (*ssdt_pcihp_ej0 - *ssdt_pcihp_start)
643 #define ACPI_PCIHP_SIZEOF (*ssdt_pcihp_end - *ssdt_pcihp_start)
644 #define ACPI_PCIHP_AML (ssdp_pcihp_aml + *ssdt_pcihp_start)
645 
646 #define ACPI_SSDT_SIGNATURE 0x54445353 /* SSDT */
647 #define ACPI_SSDT_HEADER_LENGTH 36
648 
649 #include "hw/i386/ssdt-misc.hex"
650 #include "hw/i386/ssdt-pcihp.hex"
651 
652 static void
653 build_append_notify_method(GArray *device, const char *name,
654                            const char *format, int count)
655 {
656     int i;
657     GArray *method = build_alloc_method(name, 2);
658 
659     for (i = 0; i < count; i++) {
660         GArray *target = build_alloc_array();
661         build_append_nameseg(target, format, i);
662         assert(i < 256); /* Fits in 1 byte */
663         build_append_notify_target_ifequal(method, target, i, 1);
664         build_free_array(target);
665     }
666 
667     build_append_and_cleanup_method(device, method);
668 }
669 
670 static void patch_pcihp(int slot, uint8_t *ssdt_ptr)
671 {
672     unsigned devfn = PCI_DEVFN(slot, 0);
673 
674     ssdt_ptr[ACPI_PCIHP_OFFSET_HEX] = acpi_get_hex(devfn >> 4);
675     ssdt_ptr[ACPI_PCIHP_OFFSET_HEX + 1] = acpi_get_hex(devfn);
676     ssdt_ptr[ACPI_PCIHP_OFFSET_ID] = slot;
677     ssdt_ptr[ACPI_PCIHP_OFFSET_ADR + 2] = slot;
678 }
679 
680 /* Assign BSEL property to all buses.  In the future, this can be changed
681  * to only assign to buses that support hotplug.
682  */
683 static void *acpi_set_bsel(PCIBus *bus, void *opaque)
684 {
685     unsigned *bsel_alloc = opaque;
686     unsigned *bus_bsel;
687 
688     if (bus->qbus.allow_hotplug) {
689         bus_bsel = g_malloc(sizeof *bus_bsel);
690 
691         *bus_bsel = (*bsel_alloc)++;
692         object_property_add_uint32_ptr(OBJECT(bus), ACPI_PCIHP_PROP_BSEL,
693                                        bus_bsel, NULL);
694     }
695 
696     return bsel_alloc;
697 }
698 
699 static void acpi_set_pci_info(void)
700 {
701     PCIBus *bus = find_i440fx(); /* TODO: Q35 support */
702     unsigned bsel_alloc = 0;
703 
704     if (bus) {
705         /* Scan all PCI buses. Set property to enable acpi based hotplug. */
706         pci_for_each_bus_depth_first(bus, acpi_set_bsel, NULL, &bsel_alloc);
707     }
708 }
709 
710 static void build_pci_bus_state_init(AcpiBuildPciBusHotplugState *state,
711                                      AcpiBuildPciBusHotplugState *parent)
712 {
713     state->parent = parent;
714     state->device_table = build_alloc_array();
715     state->notify_table = build_alloc_array();
716 }
717 
718 static void build_pci_bus_state_cleanup(AcpiBuildPciBusHotplugState *state)
719 {
720     build_free_array(state->device_table);
721     build_free_array(state->notify_table);
722 }
723 
724 static void *build_pci_bus_begin(PCIBus *bus, void *parent_state)
725 {
726     AcpiBuildPciBusHotplugState *parent = parent_state;
727     AcpiBuildPciBusHotplugState *child = g_malloc(sizeof *child);
728 
729     build_pci_bus_state_init(child, parent);
730 
731     return child;
732 }
733 
734 static void build_pci_bus_end(PCIBus *bus, void *bus_state)
735 {
736     AcpiBuildPciBusHotplugState *child = bus_state;
737     AcpiBuildPciBusHotplugState *parent = child->parent;
738     GArray *bus_table = build_alloc_array();
739     DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX);
740     uint8_t op;
741     int i;
742     QObject *bsel;
743     GArray *method;
744     bool bus_hotplug_support = false;
745 
746     if (bus->parent_dev) {
747         op = 0x82; /* DeviceOp */
748         build_append_nameseg(bus_table, "S%.02X_",
749                              bus->parent_dev->devfn);
750         build_append_byte(bus_table, 0x08); /* NameOp */
751         build_append_nameseg(bus_table, "_SUN");
752         build_append_value(bus_table, PCI_SLOT(bus->parent_dev->devfn), 1);
753         build_append_byte(bus_table, 0x08); /* NameOp */
754         build_append_nameseg(bus_table, "_ADR");
755         build_append_value(bus_table, (PCI_SLOT(bus->parent_dev->devfn) << 16) |
756                            PCI_FUNC(bus->parent_dev->devfn), 4);
757     } else {
758         op = 0x10; /* ScopeOp */;
759         build_append_nameseg(bus_table, "PCI0");
760     }
761 
762     bsel = object_property_get_qobject(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, NULL);
763     if (bsel) {
764         build_append_byte(bus_table, 0x08); /* NameOp */
765         build_append_nameseg(bus_table, "BSEL");
766         build_append_int(bus_table, qint_get_int(qobject_to_qint(bsel)));
767 
768         memset(slot_hotplug_enable, 0xff, sizeof slot_hotplug_enable);
769 
770         for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
771             DeviceClass *dc;
772             PCIDeviceClass *pc;
773             PCIDevice *pdev = bus->devices[i];
774 
775             if (!pdev) {
776                 continue;
777             }
778 
779             pc = PCI_DEVICE_GET_CLASS(pdev);
780             dc = DEVICE_GET_CLASS(pdev);
781 
782             if (!dc->hotpluggable || pc->is_bridge) {
783                 int slot = PCI_SLOT(i);
784 
785                 clear_bit(slot, slot_hotplug_enable);
786             }
787         }
788 
789         /* Append Device object for each slot which supports eject */
790         for (i = 0; i < PCI_SLOT_MAX; i++) {
791             bool can_eject = test_bit(i, slot_hotplug_enable);
792             if (can_eject) {
793                 void *pcihp = acpi_data_push(bus_table,
794                                              ACPI_PCIHP_SIZEOF);
795                 memcpy(pcihp, ACPI_PCIHP_AML, ACPI_PCIHP_SIZEOF);
796                 patch_pcihp(i, pcihp);
797                 bus_hotplug_support = true;
798             }
799         }
800 
801         method = build_alloc_method("DVNT", 2);
802 
803         for (i = 0; i < PCI_SLOT_MAX; i++) {
804             GArray *notify;
805             uint8_t op;
806 
807             if (!test_bit(i, slot_hotplug_enable)) {
808                 continue;
809             }
810 
811             notify = build_alloc_array();
812             op = 0xA0; /* IfOp */
813 
814             build_append_byte(notify, 0x7B); /* AndOp */
815             build_append_byte(notify, 0x68); /* Arg0Op */
816             build_append_int(notify, 0x1 << i);
817             build_append_byte(notify, 0x00); /* NullName */
818             build_append_byte(notify, 0x86); /* NotifyOp */
819             build_append_nameseg(notify, "S%.02X_", PCI_DEVFN(i, 0));
820             build_append_byte(notify, 0x69); /* Arg1Op */
821 
822             /* Pack it up */
823             build_package(notify, op, 0);
824 
825             build_append_array(method, notify);
826 
827             build_free_array(notify);
828         }
829 
830         build_append_and_cleanup_method(bus_table, method);
831     }
832 
833     /* Append PCNT method to notify about events on local and child buses.
834      * Add unconditionally for root since DSDT expects it.
835      */
836     if (bus_hotplug_support || child->notify_table->len || !bus->parent_dev) {
837         method = build_alloc_method("PCNT", 0);
838 
839         /* If bus supports hotplug select it and notify about local events */
840         if (bsel) {
841             build_append_byte(method, 0x70); /* StoreOp */
842             build_append_int(method, qint_get_int(qobject_to_qint(bsel)));
843             build_append_nameseg(method, "BNUM");
844             build_append_nameseg(method, "DVNT");
845             build_append_nameseg(method, "PCIU");
846             build_append_int(method, 1); /* Device Check */
847             build_append_nameseg(method, "DVNT");
848             build_append_nameseg(method, "PCID");
849             build_append_int(method, 3); /* Eject Request */
850         }
851 
852         /* Notify about child bus events in any case */
853         build_append_array(method, child->notify_table);
854 
855         build_append_and_cleanup_method(bus_table, method);
856 
857         /* Append description of child buses */
858         build_append_array(bus_table, child->device_table);
859 
860         /* Pack it up */
861         if (bus->parent_dev) {
862             build_extop_package(bus_table, op);
863         } else {
864             build_package(bus_table, op, 0);
865         }
866 
867         /* Append our bus description to parent table */
868         build_append_array(parent->device_table, bus_table);
869 
870         /* Also tell parent how to notify us, invoking PCNT method.
871          * At the moment this is not needed for root as we have a single root.
872          */
873         if (bus->parent_dev) {
874             build_append_byte(parent->notify_table, '^'); /* ParentPrefixChar */
875             build_append_byte(parent->notify_table, 0x2E); /* DualNamePrefix */
876             build_append_nameseg(parent->notify_table, "S%.02X_",
877                                  bus->parent_dev->devfn);
878             build_append_nameseg(parent->notify_table, "PCNT");
879         }
880     }
881 
882     build_free_array(bus_table);
883     build_pci_bus_state_cleanup(child);
884     g_free(child);
885 }
886 
887 static void patch_pci_windows(PcPciInfo *pci, uint8_t *start, unsigned size)
888 {
889     *ACPI_BUILD_PTR(start, size, acpi_pci32_start[0], uint32_t) =
890         cpu_to_le32(pci->w32.begin);
891 
892     *ACPI_BUILD_PTR(start, size, acpi_pci32_end[0], uint32_t) =
893         cpu_to_le32(pci->w32.end - 1);
894 
895     if (pci->w64.end || pci->w64.begin) {
896         *ACPI_BUILD_PTR(start, size, acpi_pci64_valid[0], uint8_t) = 1;
897         *ACPI_BUILD_PTR(start, size, acpi_pci64_start[0], uint64_t) =
898             cpu_to_le64(pci->w64.begin);
899         *ACPI_BUILD_PTR(start, size, acpi_pci64_end[0], uint64_t) =
900             cpu_to_le64(pci->w64.end - 1);
901         *ACPI_BUILD_PTR(start, size, acpi_pci64_length[0], uint64_t) =
902             cpu_to_le64(pci->w64.end - pci->w64.begin);
903     } else {
904         *ACPI_BUILD_PTR(start, size, acpi_pci64_valid[0], uint8_t) = 0;
905     }
906 }
907 
908 static void
909 build_ssdt(GArray *table_data, GArray *linker,
910            AcpiCpuInfo *cpu, AcpiPmInfo *pm, AcpiMiscInfo *misc,
911            PcPciInfo *pci, PcGuestInfo *guest_info)
912 {
913     int acpi_cpus = MIN(0xff, guest_info->apic_id_limit);
914     int ssdt_start = table_data->len;
915     uint8_t *ssdt_ptr;
916     int i;
917 
918     /* Copy header and patch values in the S3_ / S4_ / S5_ packages */
919     ssdt_ptr = acpi_data_push(table_data, sizeof(ssdp_misc_aml));
920     memcpy(ssdt_ptr, ssdp_misc_aml, sizeof(ssdp_misc_aml));
921     if (pm->s3_disabled) {
922         ssdt_ptr[acpi_s3_name[0]] = 'X';
923     }
924     if (pm->s4_disabled) {
925         ssdt_ptr[acpi_s4_name[0]] = 'X';
926     } else {
927         ssdt_ptr[acpi_s4_pkg[0] + 1] = ssdt_ptr[acpi_s4_pkg[0] + 3] =
928             pm->s4_val;
929     }
930 
931     patch_pci_windows(pci, ssdt_ptr, sizeof(ssdp_misc_aml));
932 
933     *(uint16_t *)(ssdt_ptr + *ssdt_isa_pest) =
934         cpu_to_le16(misc->pvpanic_port);
935 
936     {
937         GArray *sb_scope = build_alloc_array();
938         uint8_t op = 0x10; /* ScopeOp */
939 
940         build_append_nameseg(sb_scope, "_SB_");
941 
942         /* build Processor object for each processor */
943         for (i = 0; i < acpi_cpus; i++) {
944             uint8_t *proc = acpi_data_push(sb_scope, ACPI_PROC_SIZEOF);
945             memcpy(proc, ACPI_PROC_AML, ACPI_PROC_SIZEOF);
946             proc[ACPI_PROC_OFFSET_CPUHEX] = acpi_get_hex(i >> 4);
947             proc[ACPI_PROC_OFFSET_CPUHEX+1] = acpi_get_hex(i);
948             proc[ACPI_PROC_OFFSET_CPUID1] = i;
949             proc[ACPI_PROC_OFFSET_CPUID2] = i;
950         }
951 
952         /* build this code:
953          *   Method(NTFY, 2) {If (LEqual(Arg0, 0x00)) {Notify(CP00, Arg1)} ...}
954          */
955         /* Arg0 = Processor ID = APIC ID */
956         build_append_notify_method(sb_scope, "NTFY", "CP%0.02X", acpi_cpus);
957 
958         /* build "Name(CPON, Package() { One, One, ..., Zero, Zero, ... })" */
959         build_append_byte(sb_scope, 0x08); /* NameOp */
960         build_append_nameseg(sb_scope, "CPON");
961 
962         {
963             GArray *package = build_alloc_array();
964             uint8_t op = 0x12; /* PackageOp */
965 
966             build_append_byte(package, acpi_cpus); /* NumElements */
967             for (i = 0; i < acpi_cpus; i++) {
968                 uint8_t b = test_bit(i, cpu->found_cpus) ? 0x01 : 0x00;
969                 build_append_byte(package, b);
970             }
971 
972             build_package(package, op, 2);
973             build_append_array(sb_scope, package);
974             build_free_array(package);
975         }
976 
977         {
978             AcpiBuildPciBusHotplugState hotplug_state;
979             PCIBus *bus = find_i440fx(); /* TODO: Q35 support */
980 
981             build_pci_bus_state_init(&hotplug_state, NULL);
982 
983             if (bus) {
984                 /* Scan all PCI buses. Generate tables to support hotplug. */
985                 pci_for_each_bus_depth_first(bus, build_pci_bus_begin,
986                                              build_pci_bus_end, &hotplug_state);
987             }
988 
989             build_append_array(sb_scope, hotplug_state.device_table);
990             build_pci_bus_state_cleanup(&hotplug_state);
991         }
992 
993         build_package(sb_scope, op, 3);
994         build_append_array(table_data, sb_scope);
995         build_free_array(sb_scope);
996     }
997 
998     build_header(linker, table_data,
999                  (void *)(table_data->data + ssdt_start),
1000                  ACPI_SSDT_SIGNATURE, table_data->len - ssdt_start, 1);
1001 }
1002 
1003 static void
1004 build_hpet(GArray *table_data, GArray *linker)
1005 {
1006     Acpi20Hpet *hpet;
1007 
1008     hpet = acpi_data_push(table_data, sizeof(*hpet));
1009     /* Note timer_block_id value must be kept in sync with value advertised by
1010      * emulated hpet
1011      */
1012     hpet->timer_block_id = cpu_to_le32(0x8086a201);
1013     hpet->addr.address = cpu_to_le64(HPET_BASE);
1014     build_header(linker, table_data,
1015                  (void *)hpet, ACPI_HPET_SIGNATURE, sizeof(*hpet), 1);
1016 }
1017 
1018 static void
1019 acpi_build_srat_memory(AcpiSratMemoryAffinity *numamem,
1020                        uint64_t base, uint64_t len, int node, int enabled)
1021 {
1022     numamem->type = ACPI_SRAT_MEMORY;
1023     numamem->length = sizeof(*numamem);
1024     memset(numamem->proximity, 0, 4);
1025     numamem->proximity[0] = node;
1026     numamem->flags = cpu_to_le32(!!enabled);
1027     numamem->base_addr = cpu_to_le64(base);
1028     numamem->range_length = cpu_to_le64(len);
1029 }
1030 
1031 static void
1032 build_srat(GArray *table_data, GArray *linker,
1033            AcpiCpuInfo *cpu, PcGuestInfo *guest_info)
1034 {
1035     AcpiSystemResourceAffinityTable *srat;
1036     AcpiSratProcessorAffinity *core;
1037     AcpiSratMemoryAffinity *numamem;
1038 
1039     int i;
1040     uint64_t curnode;
1041     int srat_start, numa_start, slots;
1042     uint64_t mem_len, mem_base, next_base;
1043 
1044     srat_start = table_data->len;
1045 
1046     srat = acpi_data_push(table_data, sizeof *srat);
1047     srat->reserved1 = cpu_to_le32(1);
1048     core = (void *)(srat + 1);
1049 
1050     for (i = 0; i < guest_info->apic_id_limit; ++i) {
1051         core = acpi_data_push(table_data, sizeof *core);
1052         core->type = ACPI_SRAT_PROCESSOR;
1053         core->length = sizeof(*core);
1054         core->local_apic_id = i;
1055         curnode = guest_info->node_cpu[i];
1056         core->proximity_lo = curnode;
1057         memset(core->proximity_hi, 0, 3);
1058         core->local_sapic_eid = 0;
1059         if (test_bit(i, cpu->found_cpus)) {
1060             core->flags = cpu_to_le32(1);
1061         } else {
1062             core->flags = cpu_to_le32(0);
1063         }
1064     }
1065 
1066 
1067     /* the memory map is a bit tricky, it contains at least one hole
1068      * from 640k-1M and possibly another one from 3.5G-4G.
1069      */
1070     next_base = 0;
1071     numa_start = table_data->len;
1072 
1073     numamem = acpi_data_push(table_data, sizeof *numamem);
1074     acpi_build_srat_memory(numamem, 0, 640*1024, 0, 1);
1075     next_base = 1024 * 1024;
1076     for (i = 1; i < guest_info->numa_nodes + 1; ++i) {
1077         mem_base = next_base;
1078         mem_len = guest_info->node_mem[i - 1];
1079         if (i == 1) {
1080             mem_len -= 1024 * 1024;
1081         }
1082         next_base = mem_base + mem_len;
1083 
1084         /* Cut out the ACPI_PCI hole */
1085         if (mem_base <= guest_info->ram_size_below_4g &&
1086             next_base > guest_info->ram_size_below_4g) {
1087             mem_len -= next_base - guest_info->ram_size_below_4g;
1088             if (mem_len > 0) {
1089                 numamem = acpi_data_push(table_data, sizeof *numamem);
1090                 acpi_build_srat_memory(numamem, mem_base, mem_len, i-1, 1);
1091             }
1092             mem_base = 1ULL << 32;
1093             mem_len = next_base - guest_info->ram_size_below_4g;
1094             next_base += (1ULL << 32) - guest_info->ram_size_below_4g;
1095         }
1096         numamem = acpi_data_push(table_data, sizeof *numamem);
1097         acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1, 1);
1098     }
1099     slots = (table_data->len - numa_start) / sizeof *numamem;
1100     for (; slots < guest_info->numa_nodes + 2; slots++) {
1101         numamem = acpi_data_push(table_data, sizeof *numamem);
1102         acpi_build_srat_memory(numamem, 0, 0, 0, 0);
1103     }
1104 
1105     build_header(linker, table_data,
1106                  (void *)(table_data->data + srat_start),
1107                  ACPI_SRAT_SIGNATURE,
1108                  table_data->len - srat_start, 1);
1109 }
1110 
1111 static void
1112 build_mcfg_q35(GArray *table_data, GArray *linker, AcpiMcfgInfo *info)
1113 {
1114     AcpiTableMcfg *mcfg;
1115     uint32_t sig;
1116     int len = sizeof(*mcfg) + 1 * sizeof(mcfg->allocation[0]);
1117 
1118     mcfg = acpi_data_push(table_data, len);
1119     mcfg->allocation[0].address = cpu_to_le64(info->mcfg_base);
1120     /* Only a single allocation so no need to play with segments */
1121     mcfg->allocation[0].pci_segment = cpu_to_le16(0);
1122     mcfg->allocation[0].start_bus_number = 0;
1123     mcfg->allocation[0].end_bus_number = PCIE_MMCFG_BUS(info->mcfg_size - 1);
1124 
1125     /* MCFG is used for ECAM which can be enabled or disabled by guest.
1126      * To avoid table size changes (which create migration issues),
1127      * always create the table even if there are no allocations,
1128      * but set the signature to a reserved value in this case.
1129      * ACPI spec requires OSPMs to ignore such tables.
1130      */
1131     if (info->mcfg_base == PCIE_BASE_ADDR_UNMAPPED) {
1132         sig = ACPI_RSRV_SIGNATURE;
1133     } else {
1134         sig = ACPI_MCFG_SIGNATURE;
1135     }
1136     build_header(linker, table_data, (void *)mcfg, sig, len, 1);
1137 }
1138 
1139 static void
1140 build_dsdt(GArray *table_data, GArray *linker, AcpiMiscInfo *misc)
1141 {
1142     AcpiTableHeader *dsdt;
1143 
1144     assert(misc->dsdt_code && misc->dsdt_size);
1145 
1146     dsdt = acpi_data_push(table_data, misc->dsdt_size);
1147     memcpy(dsdt, misc->dsdt_code, misc->dsdt_size);
1148 
1149     memset(dsdt, 0, sizeof *dsdt);
1150     build_header(linker, table_data, dsdt, ACPI_DSDT_SIGNATURE,
1151                  misc->dsdt_size, 1);
1152 }
1153 
1154 /* Build final rsdt table */
1155 static void
1156 build_rsdt(GArray *table_data, GArray *linker, GArray *table_offsets)
1157 {
1158     AcpiRsdtDescriptorRev1 *rsdt;
1159     size_t rsdt_len;
1160     int i;
1161 
1162     rsdt_len = sizeof(*rsdt) + sizeof(uint32_t) * table_offsets->len;
1163     rsdt = acpi_data_push(table_data, rsdt_len);
1164     memcpy(rsdt->table_offset_entry, table_offsets->data,
1165            sizeof(uint32_t) * table_offsets->len);
1166     for (i = 0; i < table_offsets->len; ++i) {
1167         /* rsdt->table_offset_entry to be filled by Guest linker */
1168         bios_linker_loader_add_pointer(linker,
1169                                        ACPI_BUILD_TABLE_FILE,
1170                                        ACPI_BUILD_TABLE_FILE,
1171                                        table_data, &rsdt->table_offset_entry[i],
1172                                        sizeof(uint32_t));
1173     }
1174     build_header(linker, table_data,
1175                  (void *)rsdt, ACPI_RSDT_SIGNATURE, rsdt_len, 1);
1176 }
1177 
1178 static GArray *
1179 build_rsdp(GArray *rsdp_table, GArray *linker, unsigned rsdt)
1180 {
1181     AcpiRsdpDescriptor *rsdp = acpi_data_push(rsdp_table, sizeof *rsdp);
1182 
1183     bios_linker_loader_alloc(linker, ACPI_BUILD_RSDP_FILE, 1,
1184                              true /* fseg memory */);
1185 
1186     rsdp->signature = cpu_to_le64(ACPI_RSDP_SIGNATURE);
1187     memcpy(rsdp->oem_id, ACPI_BUILD_APPNAME6, 6);
1188     rsdp->rsdt_physical_address = cpu_to_le32(rsdt);
1189     /* Address to be filled by Guest linker */
1190     bios_linker_loader_add_pointer(linker, ACPI_BUILD_RSDP_FILE,
1191                                    ACPI_BUILD_TABLE_FILE,
1192                                    rsdp_table, &rsdp->rsdt_physical_address,
1193                                    sizeof rsdp->rsdt_physical_address);
1194     rsdp->checksum = 0;
1195     /* Checksum to be filled by Guest linker */
1196     bios_linker_loader_add_checksum(linker, ACPI_BUILD_RSDP_FILE,
1197                                     rsdp, rsdp, sizeof *rsdp, &rsdp->checksum);
1198 
1199     return rsdp_table;
1200 }
1201 
1202 typedef
1203 struct AcpiBuildTables {
1204     GArray *table_data;
1205     GArray *rsdp;
1206     GArray *linker;
1207 } AcpiBuildTables;
1208 
1209 static inline void acpi_build_tables_init(AcpiBuildTables *tables)
1210 {
1211     tables->rsdp = g_array_new(false, true /* clear */, 1);
1212     tables->table_data = g_array_new(false, true /* clear */, 1);
1213     tables->linker = bios_linker_loader_init();
1214 }
1215 
1216 static inline void acpi_build_tables_cleanup(AcpiBuildTables *tables, bool mfre)
1217 {
1218     void *linker_data = bios_linker_loader_cleanup(tables->linker);
1219     if (mfre) {
1220         g_free(linker_data);
1221     }
1222     g_array_free(tables->rsdp, mfre);
1223     g_array_free(tables->table_data, mfre);
1224 }
1225 
1226 typedef
1227 struct AcpiBuildState {
1228     /* Copy of table in RAM (for patching). */
1229     uint8_t *table_ram;
1230     uint32_t table_size;
1231     /* Is table patched? */
1232     uint8_t patched;
1233     PcGuestInfo *guest_info;
1234 } AcpiBuildState;
1235 
1236 static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg)
1237 {
1238     Object *pci_host;
1239     QObject *o;
1240     bool ambiguous;
1241 
1242     pci_host = object_resolve_path_type("", TYPE_PCI_HOST_BRIDGE, &ambiguous);
1243     g_assert(!ambiguous);
1244     g_assert(pci_host);
1245 
1246     o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_BASE, NULL);
1247     if (!o) {
1248         return false;
1249     }
1250     mcfg->mcfg_base = qint_get_int(qobject_to_qint(o));
1251 
1252     o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_SIZE, NULL);
1253     assert(o);
1254     mcfg->mcfg_size = qint_get_int(qobject_to_qint(o));
1255     return true;
1256 }
1257 
1258 static
1259 void acpi_build(PcGuestInfo *guest_info, AcpiBuildTables *tables)
1260 {
1261     GArray *table_offsets;
1262     unsigned facs, dsdt, rsdt;
1263     AcpiCpuInfo cpu;
1264     AcpiPmInfo pm;
1265     AcpiMiscInfo misc;
1266     AcpiMcfgInfo mcfg;
1267     PcPciInfo pci;
1268     uint8_t *u;
1269 
1270     acpi_get_cpu_info(&cpu);
1271     acpi_get_pm_info(&pm);
1272     acpi_get_dsdt(&misc);
1273     acpi_get_misc_info(&misc);
1274     acpi_get_pci_info(&pci);
1275 
1276     table_offsets = g_array_new(false, true /* clear */,
1277                                         sizeof(uint32_t));
1278     ACPI_BUILD_DPRINTF(3, "init ACPI tables\n");
1279 
1280     bios_linker_loader_alloc(tables->linker, ACPI_BUILD_TABLE_FILE,
1281                              64 /* Ensure FACS is aligned */,
1282                              false /* high memory */);
1283 
1284     /*
1285      * FACS is pointed to by FADT.
1286      * We place it first since it's the only table that has alignment
1287      * requirements.
1288      */
1289     facs = tables->table_data->len;
1290     build_facs(tables->table_data, tables->linker, guest_info);
1291 
1292     /* DSDT is pointed to by FADT */
1293     dsdt = tables->table_data->len;
1294     build_dsdt(tables->table_data, tables->linker, &misc);
1295 
1296     /* ACPI tables pointed to by RSDT */
1297     acpi_add_table(table_offsets, tables->table_data);
1298     build_fadt(tables->table_data, tables->linker, &pm, facs, dsdt);
1299     acpi_add_table(table_offsets, tables->table_data);
1300 
1301     build_ssdt(tables->table_data, tables->linker, &cpu, &pm, &misc, &pci,
1302                guest_info);
1303     acpi_add_table(table_offsets, tables->table_data);
1304 
1305     build_madt(tables->table_data, tables->linker, &cpu, guest_info);
1306     acpi_add_table(table_offsets, tables->table_data);
1307     if (misc.has_hpet) {
1308         build_hpet(tables->table_data, tables->linker);
1309     }
1310     if (guest_info->numa_nodes) {
1311         acpi_add_table(table_offsets, tables->table_data);
1312         build_srat(tables->table_data, tables->linker, &cpu, guest_info);
1313     }
1314     if (acpi_get_mcfg(&mcfg)) {
1315         acpi_add_table(table_offsets, tables->table_data);
1316         build_mcfg_q35(tables->table_data, tables->linker, &mcfg);
1317     }
1318 
1319     /* Add tables supplied by user (if any) */
1320     for (u = acpi_table_first(); u; u = acpi_table_next(u)) {
1321         unsigned len = acpi_table_len(u);
1322 
1323         acpi_add_table(table_offsets, tables->table_data);
1324         g_array_append_vals(tables->table_data, u, len);
1325     }
1326 
1327     /* RSDT is pointed to by RSDP */
1328     rsdt = tables->table_data->len;
1329     build_rsdt(tables->table_data, tables->linker, table_offsets);
1330 
1331     /* RSDP is in FSEG memory, so allocate it separately */
1332     build_rsdp(tables->rsdp, tables->linker, rsdt);
1333 
1334     /* We'll expose it all to Guest so align size to reduce
1335      * chance of size changes.
1336      * RSDP is small so it's easy to keep it immutable, no need to
1337      * bother with alignment.
1338      */
1339     acpi_align_size(tables->table_data, 0x1000);
1340 
1341     acpi_align_size(tables->linker, 0x1000);
1342 
1343     /* Cleanup memory that's no longer used. */
1344     g_array_free(table_offsets, true);
1345 }
1346 
1347 static void acpi_build_update(void *build_opaque, uint32_t offset)
1348 {
1349     AcpiBuildState *build_state = build_opaque;
1350     AcpiBuildTables tables;
1351 
1352     /* No state to update or already patched? Nothing to do. */
1353     if (!build_state || build_state->patched) {
1354         return;
1355     }
1356     build_state->patched = 1;
1357 
1358     acpi_build_tables_init(&tables);
1359 
1360     acpi_build(build_state->guest_info, &tables);
1361 
1362     assert(acpi_data_len(tables.table_data) == build_state->table_size);
1363     memcpy(build_state->table_ram, tables.table_data->data,
1364            build_state->table_size);
1365 
1366     acpi_build_tables_cleanup(&tables, true);
1367 }
1368 
1369 static void acpi_build_reset(void *build_opaque)
1370 {
1371     AcpiBuildState *build_state = build_opaque;
1372     build_state->patched = 0;
1373 }
1374 
1375 static void *acpi_add_rom_blob(AcpiBuildState *build_state, GArray *blob,
1376                                const char *name)
1377 {
1378     return rom_add_blob(name, blob->data, acpi_data_len(blob), -1, name,
1379                         acpi_build_update, build_state);
1380 }
1381 
1382 static const VMStateDescription vmstate_acpi_build = {
1383     .name = "acpi_build",
1384     .version_id = 1,
1385     .minimum_version_id = 1,
1386     .minimum_version_id_old = 1,
1387     .fields      = (VMStateField[]) {
1388         VMSTATE_UINT8(patched, AcpiBuildState),
1389         VMSTATE_END_OF_LIST()
1390     },
1391 };
1392 
1393 void acpi_setup(PcGuestInfo *guest_info)
1394 {
1395     AcpiBuildTables tables;
1396     AcpiBuildState *build_state;
1397 
1398     if (!guest_info->fw_cfg) {
1399         ACPI_BUILD_DPRINTF(3, "No fw cfg. Bailing out.\n");
1400         return;
1401     }
1402 
1403     if (!guest_info->has_acpi_build) {
1404         ACPI_BUILD_DPRINTF(3, "ACPI build disabled. Bailing out.\n");
1405         return;
1406     }
1407 
1408     if (!acpi_enabled) {
1409         ACPI_BUILD_DPRINTF(3, "ACPI disabled. Bailing out.\n");
1410         return;
1411     }
1412 
1413     build_state = g_malloc0(sizeof *build_state);
1414 
1415     build_state->guest_info = guest_info;
1416 
1417     acpi_set_pci_info();
1418 
1419     acpi_build_tables_init(&tables);
1420     acpi_build(build_state->guest_info, &tables);
1421 
1422     /* Now expose it all to Guest */
1423     build_state->table_ram = acpi_add_rom_blob(build_state, tables.table_data,
1424                                                ACPI_BUILD_TABLE_FILE);
1425     build_state->table_size = acpi_data_len(tables.table_data);
1426 
1427     acpi_add_rom_blob(NULL, tables.linker, "etc/table-loader");
1428 
1429     /*
1430      * RSDP is small so it's easy to keep it immutable, no need to
1431      * bother with ROM blobs.
1432      */
1433     fw_cfg_add_file(guest_info->fw_cfg, ACPI_BUILD_RSDP_FILE,
1434                     tables.rsdp->data, acpi_data_len(tables.rsdp));
1435 
1436     qemu_register_reset(acpi_build_reset, build_state);
1437     acpi_build_reset(build_state);
1438     vmstate_register(NULL, 0, &vmstate_acpi_build, build_state);
1439 
1440     /* Cleanup tables but don't free the memory: we track it
1441      * in build_state.
1442      */
1443     acpi_build_tables_cleanup(&tables, false);
1444 }
1445