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