xref: /openbmc/qemu/hw/arm/virt.c (revision a6896ebc)
1 /*
2  * ARM mach-virt emulation
3  *
4  * Copyright (c) 2013 Linaro Limited
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2 or later, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * Emulate a virtual board which works by passing Linux all the information
19  * it needs about what devices are present via the device tree.
20  * There are some restrictions about what we can do here:
21  *  + we can only present devices whose Linux drivers will work based
22  *    purely on the device tree with no platform data at all
23  *  + we want to present a very stripped-down minimalist platform,
24  *    both because this reduces the security attack surface from the guest
25  *    and also because it reduces our exposure to being broken when
26  *    the kernel updates its device tree bindings and requires further
27  *    information in a device binding that we aren't providing.
28  * This is essentially the same approach kvmtool uses.
29  */
30 
31 #include "qemu/osdep.h"
32 #include "qemu/datadir.h"
33 #include "qemu/units.h"
34 #include "qemu/option.h"
35 #include "monitor/qdev.h"
36 #include "hw/sysbus.h"
37 #include "hw/arm/boot.h"
38 #include "hw/arm/primecell.h"
39 #include "hw/arm/virt.h"
40 #include "hw/block/flash.h"
41 #include "hw/vfio/vfio-calxeda-xgmac.h"
42 #include "hw/vfio/vfio-amd-xgbe.h"
43 #include "hw/display/ramfb.h"
44 #include "net/net.h"
45 #include "sysemu/device_tree.h"
46 #include "sysemu/numa.h"
47 #include "sysemu/runstate.h"
48 #include "sysemu/tpm.h"
49 #include "sysemu/tcg.h"
50 #include "sysemu/kvm.h"
51 #include "sysemu/hvf.h"
52 #include "sysemu/qtest.h"
53 #include "hw/loader.h"
54 #include "qapi/error.h"
55 #include "qemu/bitops.h"
56 #include "qemu/error-report.h"
57 #include "qemu/module.h"
58 #include "hw/pci-host/gpex.h"
59 #include "hw/virtio/virtio-pci.h"
60 #include "hw/core/sysbus-fdt.h"
61 #include "hw/platform-bus.h"
62 #include "hw/qdev-properties.h"
63 #include "hw/arm/fdt.h"
64 #include "hw/intc/arm_gic.h"
65 #include "hw/intc/arm_gicv3_common.h"
66 #include "hw/intc/arm_gicv3_its_common.h"
67 #include "hw/irq.h"
68 #include "kvm_arm.h"
69 #include "hw/firmware/smbios.h"
70 #include "qapi/visitor.h"
71 #include "qapi/qapi-visit-common.h"
72 #include "qapi/qmp/qlist.h"
73 #include "standard-headers/linux/input.h"
74 #include "hw/arm/smmuv3.h"
75 #include "hw/acpi/acpi.h"
76 #include "target/arm/cpu-qom.h"
77 #include "target/arm/internals.h"
78 #include "target/arm/multiprocessing.h"
79 #include "target/arm/gtimer.h"
80 #include "hw/mem/pc-dimm.h"
81 #include "hw/mem/nvdimm.h"
82 #include "hw/acpi/generic_event_device.h"
83 #include "hw/virtio/virtio-md-pci.h"
84 #include "hw/virtio/virtio-iommu.h"
85 #include "hw/char/pl011.h"
86 #include "qemu/guest-random.h"
87 
88 static GlobalProperty arm_virt_compat[] = {
89     { TYPE_VIRTIO_IOMMU_PCI, "aw-bits", "48" },
90 };
91 static const size_t arm_virt_compat_len = G_N_ELEMENTS(arm_virt_compat);
92 
93 /*
94  * This cannot be called from the virt_machine_class_init() because
95  * TYPE_VIRT_MACHINE is abstract and mc->compat_props g_ptr_array_new()
96  * only is called on virt non abstract class init.
97  */
98 static void arm_virt_compat_set(MachineClass *mc)
99 {
100     compat_props_add(mc->compat_props, arm_virt_compat,
101                      arm_virt_compat_len);
102 }
103 
104 #define DEFINE_VIRT_MACHINE_IMPL(latest, ...) \
105     static void MACHINE_VER_SYM(class_init, virt, __VA_ARGS__)( \
106         ObjectClass *oc, \
107         void *data) \
108     { \
109         MachineClass *mc = MACHINE_CLASS(oc); \
110         arm_virt_compat_set(mc); \
111         MACHINE_VER_SYM(options, virt, __VA_ARGS__)(mc); \
112         mc->desc = "QEMU " MACHINE_VER_STR(__VA_ARGS__) " ARM Virtual Machine"; \
113         MACHINE_VER_DEPRECATION(__VA_ARGS__); \
114         if (latest) { \
115             mc->alias = "virt"; \
116         } \
117     } \
118     static const TypeInfo MACHINE_VER_SYM(info, virt, __VA_ARGS__) = \
119     { \
120         .name = MACHINE_VER_TYPE_NAME("virt", __VA_ARGS__), \
121         .parent = TYPE_VIRT_MACHINE, \
122         .class_init = MACHINE_VER_SYM(class_init, virt, __VA_ARGS__), \
123     }; \
124     static void MACHINE_VER_SYM(register, virt, __VA_ARGS__)(void) \
125     { \
126         MACHINE_VER_DELETION(__VA_ARGS__); \
127         type_register_static(&MACHINE_VER_SYM(info, virt, __VA_ARGS__)); \
128     } \
129     type_init(MACHINE_VER_SYM(register, virt, __VA_ARGS__));
130 
131 #define DEFINE_VIRT_MACHINE_AS_LATEST(major, minor) \
132     DEFINE_VIRT_MACHINE_IMPL(true, major, minor)
133 #define DEFINE_VIRT_MACHINE(major, minor) \
134     DEFINE_VIRT_MACHINE_IMPL(false, major, minor)
135 
136 
137 /* Number of external interrupt lines to configure the GIC with */
138 #define NUM_IRQS 256
139 
140 #define PLATFORM_BUS_NUM_IRQS 64
141 
142 /* Legacy RAM limit in GB (< version 4.0) */
143 #define LEGACY_RAMLIMIT_GB 255
144 #define LEGACY_RAMLIMIT_BYTES (LEGACY_RAMLIMIT_GB * GiB)
145 
146 /* Addresses and sizes of our components.
147  * 0..128MB is space for a flash device so we can run bootrom code such as UEFI.
148  * 128MB..256MB is used for miscellaneous device I/O.
149  * 256MB..1GB is reserved for possible future PCI support (ie where the
150  * PCI memory window will go if we add a PCI host controller).
151  * 1GB and up is RAM (which may happily spill over into the
152  * high memory region beyond 4GB).
153  * This represents a compromise between how much RAM can be given to
154  * a 32 bit VM and leaving space for expansion and in particular for PCI.
155  * Note that devices should generally be placed at multiples of 0x10000,
156  * to accommodate guests using 64K pages.
157  */
158 static const MemMapEntry base_memmap[] = {
159     /* Space up to 0x8000000 is reserved for a boot ROM */
160     [VIRT_FLASH] =              {          0, 0x08000000 },
161     [VIRT_CPUPERIPHS] =         { 0x08000000, 0x00020000 },
162     /* GIC distributor and CPU interfaces sit inside the CPU peripheral space */
163     [VIRT_GIC_DIST] =           { 0x08000000, 0x00010000 },
164     [VIRT_GIC_CPU] =            { 0x08010000, 0x00010000 },
165     [VIRT_GIC_V2M] =            { 0x08020000, 0x00001000 },
166     [VIRT_GIC_HYP] =            { 0x08030000, 0x00010000 },
167     [VIRT_GIC_VCPU] =           { 0x08040000, 0x00010000 },
168     /* The space in between here is reserved for GICv3 CPU/vCPU/HYP */
169     [VIRT_GIC_ITS] =            { 0x08080000, 0x00020000 },
170     /* This redistributor space allows up to 2*64kB*123 CPUs */
171     [VIRT_GIC_REDIST] =         { 0x080A0000, 0x00F60000 },
172     [VIRT_UART0] =              { 0x09000000, 0x00001000 },
173     [VIRT_RTC] =                { 0x09010000, 0x00001000 },
174     [VIRT_FW_CFG] =             { 0x09020000, 0x00000018 },
175     [VIRT_GPIO] =               { 0x09030000, 0x00001000 },
176     [VIRT_UART1] =              { 0x09040000, 0x00001000 },
177     [VIRT_SMMU] =               { 0x09050000, 0x00020000 },
178     [VIRT_PCDIMM_ACPI] =        { 0x09070000, MEMORY_HOTPLUG_IO_LEN },
179     [VIRT_ACPI_GED] =           { 0x09080000, ACPI_GED_EVT_SEL_LEN },
180     [VIRT_NVDIMM_ACPI] =        { 0x09090000, NVDIMM_ACPI_IO_LEN},
181     [VIRT_PVTIME] =             { 0x090a0000, 0x00010000 },
182     [VIRT_SECURE_GPIO] =        { 0x090b0000, 0x00001000 },
183     [VIRT_MMIO] =               { 0x0a000000, 0x00000200 },
184     /* ...repeating for a total of NUM_VIRTIO_TRANSPORTS, each of that size */
185     [VIRT_PLATFORM_BUS] =       { 0x0c000000, 0x02000000 },
186     [VIRT_SECURE_MEM] =         { 0x0e000000, 0x01000000 },
187     [VIRT_PCIE_MMIO] =          { 0x10000000, 0x2eff0000 },
188     [VIRT_PCIE_PIO] =           { 0x3eff0000, 0x00010000 },
189     [VIRT_PCIE_ECAM] =          { 0x3f000000, 0x01000000 },
190     /* Actual RAM size depends on initial RAM and device memory settings */
191     [VIRT_MEM] =                { GiB, LEGACY_RAMLIMIT_BYTES },
192 };
193 
194 /*
195  * Highmem IO Regions: This memory map is floating, located after the RAM.
196  * Each MemMapEntry base (GPA) will be dynamically computed, depending on the
197  * top of the RAM, so that its base get the same alignment as the size,
198  * ie. a 512GiB entry will be aligned on a 512GiB boundary. If there is
199  * less than 256GiB of RAM, the floating area starts at the 256GiB mark.
200  * Note the extended_memmap is sized so that it eventually also includes the
201  * base_memmap entries (VIRT_HIGH_GIC_REDIST2 index is greater than the last
202  * index of base_memmap).
203  *
204  * The memory map for these Highmem IO Regions can be in legacy or compact
205  * layout, depending on 'compact-highmem' property. With legacy layout, the
206  * PA space for one specific region is always reserved, even if the region
207  * has been disabled or doesn't fit into the PA space. However, the PA space
208  * for the region won't be reserved in these circumstances with compact layout.
209  */
210 static MemMapEntry extended_memmap[] = {
211     /* Additional 64 MB redist region (can contain up to 512 redistributors) */
212     [VIRT_HIGH_GIC_REDIST2] =   { 0x0, 64 * MiB },
213     [VIRT_HIGH_PCIE_ECAM] =     { 0x0, 256 * MiB },
214     /* Second PCIe window */
215     [VIRT_HIGH_PCIE_MMIO] =     { 0x0, 512 * GiB },
216 };
217 
218 static const int a15irqmap[] = {
219     [VIRT_UART0] = 1,
220     [VIRT_RTC] = 2,
221     [VIRT_PCIE] = 3, /* ... to 6 */
222     [VIRT_GPIO] = 7,
223     [VIRT_UART1] = 8,
224     [VIRT_ACPI_GED] = 9,
225     [VIRT_MMIO] = 16, /* ...to 16 + NUM_VIRTIO_TRANSPORTS - 1 */
226     [VIRT_GIC_V2M] = 48, /* ...to 48 + NUM_GICV2M_SPIS - 1 */
227     [VIRT_SMMU] = 74,    /* ...to 74 + NUM_SMMU_IRQS - 1 */
228     [VIRT_PLATFORM_BUS] = 112, /* ...to 112 + PLATFORM_BUS_NUM_IRQS -1 */
229 };
230 
231 static void create_randomness(MachineState *ms, const char *node)
232 {
233     struct {
234         uint64_t kaslr;
235         uint8_t rng[32];
236     } seed;
237 
238     if (qemu_guest_getrandom(&seed, sizeof(seed), NULL)) {
239         return;
240     }
241     qemu_fdt_setprop_u64(ms->fdt, node, "kaslr-seed", seed.kaslr);
242     qemu_fdt_setprop(ms->fdt, node, "rng-seed", seed.rng, sizeof(seed.rng));
243 }
244 
245 /*
246  * The CPU object always exposes the NS EL2 virt timer IRQ line,
247  * but we don't want to advertise it to the guest in the dtb or ACPI
248  * table unless it's really going to do something.
249  */
250 static bool ns_el2_virt_timer_present(void)
251 {
252     ARMCPU *cpu = ARM_CPU(qemu_get_cpu(0));
253     CPUARMState *env = &cpu->env;
254 
255     return arm_feature(env, ARM_FEATURE_AARCH64) &&
256         arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu);
257 }
258 
259 static void create_fdt(VirtMachineState *vms)
260 {
261     MachineState *ms = MACHINE(vms);
262     int nb_numa_nodes = ms->numa_state->num_nodes;
263     void *fdt = create_device_tree(&vms->fdt_size);
264 
265     if (!fdt) {
266         error_report("create_device_tree() failed");
267         exit(1);
268     }
269 
270     ms->fdt = fdt;
271 
272     /* Header */
273     qemu_fdt_setprop_string(fdt, "/", "compatible", "linux,dummy-virt");
274     qemu_fdt_setprop_cell(fdt, "/", "#address-cells", 0x2);
275     qemu_fdt_setprop_cell(fdt, "/", "#size-cells", 0x2);
276     qemu_fdt_setprop_string(fdt, "/", "model", "linux,dummy-virt");
277 
278     /*
279      * For QEMU, all DMA is coherent. Advertising this in the root node
280      * has two benefits:
281      *
282      * - It avoids potential bugs where we forget to mark a DMA
283      *   capable device as being dma-coherent
284      * - It avoids spurious warnings from the Linux kernel about
285      *   devices which can't do DMA at all
286      */
287     qemu_fdt_setprop(fdt, "/", "dma-coherent", NULL, 0);
288 
289     /* /chosen must exist for load_dtb to fill in necessary properties later */
290     qemu_fdt_add_subnode(fdt, "/chosen");
291     if (vms->dtb_randomness) {
292         create_randomness(ms, "/chosen");
293     }
294 
295     if (vms->secure) {
296         qemu_fdt_add_subnode(fdt, "/secure-chosen");
297         if (vms->dtb_randomness) {
298             create_randomness(ms, "/secure-chosen");
299         }
300     }
301 
302     qemu_fdt_add_subnode(fdt, "/aliases");
303 
304     /* Clock node, for the benefit of the UART. The kernel device tree
305      * binding documentation claims the PL011 node clock properties are
306      * optional but in practice if you omit them the kernel refuses to
307      * probe for the device.
308      */
309     vms->clock_phandle = qemu_fdt_alloc_phandle(fdt);
310     qemu_fdt_add_subnode(fdt, "/apb-pclk");
311     qemu_fdt_setprop_string(fdt, "/apb-pclk", "compatible", "fixed-clock");
312     qemu_fdt_setprop_cell(fdt, "/apb-pclk", "#clock-cells", 0x0);
313     qemu_fdt_setprop_cell(fdt, "/apb-pclk", "clock-frequency", 24000000);
314     qemu_fdt_setprop_string(fdt, "/apb-pclk", "clock-output-names",
315                                 "clk24mhz");
316     qemu_fdt_setprop_cell(fdt, "/apb-pclk", "phandle", vms->clock_phandle);
317 
318     if (nb_numa_nodes > 0 && ms->numa_state->have_numa_distance) {
319         int size = nb_numa_nodes * nb_numa_nodes * 3 * sizeof(uint32_t);
320         uint32_t *matrix = g_malloc0(size);
321         int idx, i, j;
322 
323         for (i = 0; i < nb_numa_nodes; i++) {
324             for (j = 0; j < nb_numa_nodes; j++) {
325                 idx = (i * nb_numa_nodes + j) * 3;
326                 matrix[idx + 0] = cpu_to_be32(i);
327                 matrix[idx + 1] = cpu_to_be32(j);
328                 matrix[idx + 2] =
329                     cpu_to_be32(ms->numa_state->nodes[i].distance[j]);
330             }
331         }
332 
333         qemu_fdt_add_subnode(fdt, "/distance-map");
334         qemu_fdt_setprop_string(fdt, "/distance-map", "compatible",
335                                 "numa-distance-map-v1");
336         qemu_fdt_setprop(fdt, "/distance-map", "distance-matrix",
337                          matrix, size);
338         g_free(matrix);
339     }
340 }
341 
342 static void fdt_add_timer_nodes(const VirtMachineState *vms)
343 {
344     /* On real hardware these interrupts are level-triggered.
345      * On KVM they were edge-triggered before host kernel version 4.4,
346      * and level-triggered afterwards.
347      * On emulated QEMU they are level-triggered.
348      *
349      * Getting the DTB info about them wrong is awkward for some
350      * guest kernels:
351      *  pre-4.8 ignore the DT and leave the interrupt configured
352      *   with whatever the GIC reset value (or the bootloader) left it at
353      *  4.8 before rc6 honour the incorrect data by programming it back
354      *   into the GIC, causing problems
355      *  4.8rc6 and later ignore the DT and always write "level triggered"
356      *   into the GIC
357      *
358      * For backwards-compatibility, virt-2.8 and earlier will continue
359      * to say these are edge-triggered, but later machines will report
360      * the correct information.
361      */
362     ARMCPU *armcpu;
363     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
364     uint32_t irqflags = GIC_FDT_IRQ_FLAGS_LEVEL_HI;
365     MachineState *ms = MACHINE(vms);
366 
367     if (vmc->claim_edge_triggered_timers) {
368         irqflags = GIC_FDT_IRQ_FLAGS_EDGE_LO_HI;
369     }
370 
371     if (vms->gic_version == VIRT_GIC_VERSION_2) {
372         irqflags = deposit32(irqflags, GIC_FDT_IRQ_PPI_CPU_START,
373                              GIC_FDT_IRQ_PPI_CPU_WIDTH,
374                              (1 << MACHINE(vms)->smp.cpus) - 1);
375     }
376 
377     qemu_fdt_add_subnode(ms->fdt, "/timer");
378 
379     armcpu = ARM_CPU(qemu_get_cpu(0));
380     if (arm_feature(&armcpu->env, ARM_FEATURE_V8)) {
381         const char compat[] = "arm,armv8-timer\0arm,armv7-timer";
382         qemu_fdt_setprop(ms->fdt, "/timer", "compatible",
383                          compat, sizeof(compat));
384     } else {
385         qemu_fdt_setprop_string(ms->fdt, "/timer", "compatible",
386                                 "arm,armv7-timer");
387     }
388     qemu_fdt_setprop(ms->fdt, "/timer", "always-on", NULL, 0);
389     if (vms->ns_el2_virt_timer_irq) {
390         qemu_fdt_setprop_cells(ms->fdt, "/timer", "interrupts",
391                                GIC_FDT_IRQ_TYPE_PPI,
392                                INTID_TO_PPI(ARCH_TIMER_S_EL1_IRQ), irqflags,
393                                GIC_FDT_IRQ_TYPE_PPI,
394                                INTID_TO_PPI(ARCH_TIMER_NS_EL1_IRQ), irqflags,
395                                GIC_FDT_IRQ_TYPE_PPI,
396                                INTID_TO_PPI(ARCH_TIMER_VIRT_IRQ), irqflags,
397                                GIC_FDT_IRQ_TYPE_PPI,
398                                INTID_TO_PPI(ARCH_TIMER_NS_EL2_IRQ), irqflags,
399                                GIC_FDT_IRQ_TYPE_PPI,
400                                INTID_TO_PPI(ARCH_TIMER_NS_EL2_VIRT_IRQ), irqflags);
401     } else {
402         qemu_fdt_setprop_cells(ms->fdt, "/timer", "interrupts",
403                                GIC_FDT_IRQ_TYPE_PPI,
404                                INTID_TO_PPI(ARCH_TIMER_S_EL1_IRQ), irqflags,
405                                GIC_FDT_IRQ_TYPE_PPI,
406                                INTID_TO_PPI(ARCH_TIMER_NS_EL1_IRQ), irqflags,
407                                GIC_FDT_IRQ_TYPE_PPI,
408                                INTID_TO_PPI(ARCH_TIMER_VIRT_IRQ), irqflags,
409                                GIC_FDT_IRQ_TYPE_PPI,
410                                INTID_TO_PPI(ARCH_TIMER_NS_EL2_IRQ), irqflags);
411     }
412 }
413 
414 static void fdt_add_cpu_nodes(const VirtMachineState *vms)
415 {
416     int cpu;
417     int addr_cells = 1;
418     const MachineState *ms = MACHINE(vms);
419     const VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
420     int smp_cpus = ms->smp.cpus;
421 
422     /*
423      * See Linux Documentation/devicetree/bindings/arm/cpus.yaml
424      * On ARM v8 64-bit systems value should be set to 2,
425      * that corresponds to the MPIDR_EL1 register size.
426      * If MPIDR_EL1[63:32] value is equal to 0 on all CPUs
427      * in the system, #address-cells can be set to 1, since
428      * MPIDR_EL1[63:32] bits are not used for CPUs
429      * identification.
430      *
431      * Here we actually don't know whether our system is 32- or 64-bit one.
432      * The simplest way to go is to examine affinity IDs of all our CPUs. If
433      * at least one of them has Aff3 populated, we set #address-cells to 2.
434      */
435     for (cpu = 0; cpu < smp_cpus; cpu++) {
436         ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(cpu));
437 
438         if (arm_cpu_mp_affinity(armcpu) & ARM_AFF3_MASK) {
439             addr_cells = 2;
440             break;
441         }
442     }
443 
444     qemu_fdt_add_subnode(ms->fdt, "/cpus");
445     qemu_fdt_setprop_cell(ms->fdt, "/cpus", "#address-cells", addr_cells);
446     qemu_fdt_setprop_cell(ms->fdt, "/cpus", "#size-cells", 0x0);
447 
448     for (cpu = smp_cpus - 1; cpu >= 0; cpu--) {
449         char *nodename = g_strdup_printf("/cpus/cpu@%d", cpu);
450         ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(cpu));
451         CPUState *cs = CPU(armcpu);
452 
453         qemu_fdt_add_subnode(ms->fdt, nodename);
454         qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "cpu");
455         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
456                                     armcpu->dtb_compatible);
457 
458         if (vms->psci_conduit != QEMU_PSCI_CONDUIT_DISABLED && smp_cpus > 1) {
459             qemu_fdt_setprop_string(ms->fdt, nodename,
460                                         "enable-method", "psci");
461         }
462 
463         if (addr_cells == 2) {
464             qemu_fdt_setprop_u64(ms->fdt, nodename, "reg",
465                                  arm_cpu_mp_affinity(armcpu));
466         } else {
467             qemu_fdt_setprop_cell(ms->fdt, nodename, "reg",
468                                   arm_cpu_mp_affinity(armcpu));
469         }
470 
471         if (ms->possible_cpus->cpus[cs->cpu_index].props.has_node_id) {
472             qemu_fdt_setprop_cell(ms->fdt, nodename, "numa-node-id",
473                 ms->possible_cpus->cpus[cs->cpu_index].props.node_id);
474         }
475 
476         if (!vmc->no_cpu_topology) {
477             qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle",
478                                   qemu_fdt_alloc_phandle(ms->fdt));
479         }
480 
481         g_free(nodename);
482     }
483 
484     if (!vmc->no_cpu_topology) {
485         /*
486          * Add vCPU topology description through fdt node cpu-map.
487          *
488          * See Linux Documentation/devicetree/bindings/cpu/cpu-topology.txt
489          * In a SMP system, the hierarchy of CPUs can be defined through
490          * four entities that are used to describe the layout of CPUs in
491          * the system: socket/cluster/core/thread.
492          *
493          * A socket node represents the boundary of system physical package
494          * and its child nodes must be one or more cluster nodes. A system
495          * can contain several layers of clustering within a single physical
496          * package and cluster nodes can be contained in parent cluster nodes.
497          *
498          * Note: currently we only support one layer of clustering within
499          * each physical package.
500          */
501         qemu_fdt_add_subnode(ms->fdt, "/cpus/cpu-map");
502 
503         for (cpu = smp_cpus - 1; cpu >= 0; cpu--) {
504             char *cpu_path = g_strdup_printf("/cpus/cpu@%d", cpu);
505             char *map_path;
506 
507             if (ms->smp.threads > 1) {
508                 map_path = g_strdup_printf(
509                     "/cpus/cpu-map/socket%d/cluster%d/core%d/thread%d",
510                     cpu / (ms->smp.clusters * ms->smp.cores * ms->smp.threads),
511                     (cpu / (ms->smp.cores * ms->smp.threads)) % ms->smp.clusters,
512                     (cpu / ms->smp.threads) % ms->smp.cores,
513                     cpu % ms->smp.threads);
514             } else {
515                 map_path = g_strdup_printf(
516                     "/cpus/cpu-map/socket%d/cluster%d/core%d",
517                     cpu / (ms->smp.clusters * ms->smp.cores),
518                     (cpu / ms->smp.cores) % ms->smp.clusters,
519                     cpu % ms->smp.cores);
520             }
521             qemu_fdt_add_path(ms->fdt, map_path);
522             qemu_fdt_setprop_phandle(ms->fdt, map_path, "cpu", cpu_path);
523 
524             g_free(map_path);
525             g_free(cpu_path);
526         }
527     }
528 }
529 
530 static void fdt_add_its_gic_node(VirtMachineState *vms)
531 {
532     char *nodename;
533     MachineState *ms = MACHINE(vms);
534 
535     vms->msi_phandle = qemu_fdt_alloc_phandle(ms->fdt);
536     nodename = g_strdup_printf("/intc/its@%" PRIx64,
537                                vms->memmap[VIRT_GIC_ITS].base);
538     qemu_fdt_add_subnode(ms->fdt, nodename);
539     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
540                             "arm,gic-v3-its");
541     qemu_fdt_setprop(ms->fdt, nodename, "msi-controller", NULL, 0);
542     qemu_fdt_setprop_cell(ms->fdt, nodename, "#msi-cells", 1);
543     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
544                                  2, vms->memmap[VIRT_GIC_ITS].base,
545                                  2, vms->memmap[VIRT_GIC_ITS].size);
546     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", vms->msi_phandle);
547     g_free(nodename);
548 }
549 
550 static void fdt_add_v2m_gic_node(VirtMachineState *vms)
551 {
552     MachineState *ms = MACHINE(vms);
553     char *nodename;
554 
555     nodename = g_strdup_printf("/intc/v2m@%" PRIx64,
556                                vms->memmap[VIRT_GIC_V2M].base);
557     vms->msi_phandle = qemu_fdt_alloc_phandle(ms->fdt);
558     qemu_fdt_add_subnode(ms->fdt, nodename);
559     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
560                             "arm,gic-v2m-frame");
561     qemu_fdt_setprop(ms->fdt, nodename, "msi-controller", NULL, 0);
562     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
563                                  2, vms->memmap[VIRT_GIC_V2M].base,
564                                  2, vms->memmap[VIRT_GIC_V2M].size);
565     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", vms->msi_phandle);
566     g_free(nodename);
567 }
568 
569 static void fdt_add_gic_node(VirtMachineState *vms)
570 {
571     MachineState *ms = MACHINE(vms);
572     char *nodename;
573 
574     vms->gic_phandle = qemu_fdt_alloc_phandle(ms->fdt);
575     qemu_fdt_setprop_cell(ms->fdt, "/", "interrupt-parent", vms->gic_phandle);
576 
577     nodename = g_strdup_printf("/intc@%" PRIx64,
578                                vms->memmap[VIRT_GIC_DIST].base);
579     qemu_fdt_add_subnode(ms->fdt, nodename);
580     qemu_fdt_setprop_cell(ms->fdt, nodename, "#interrupt-cells", 3);
581     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-controller", NULL, 0);
582     qemu_fdt_setprop_cell(ms->fdt, nodename, "#address-cells", 0x2);
583     qemu_fdt_setprop_cell(ms->fdt, nodename, "#size-cells", 0x2);
584     qemu_fdt_setprop(ms->fdt, nodename, "ranges", NULL, 0);
585     if (vms->gic_version != VIRT_GIC_VERSION_2) {
586         int nb_redist_regions = virt_gicv3_redist_region_count(vms);
587 
588         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
589                                 "arm,gic-v3");
590 
591         qemu_fdt_setprop_cell(ms->fdt, nodename,
592                               "#redistributor-regions", nb_redist_regions);
593 
594         if (nb_redist_regions == 1) {
595             qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
596                                          2, vms->memmap[VIRT_GIC_DIST].base,
597                                          2, vms->memmap[VIRT_GIC_DIST].size,
598                                          2, vms->memmap[VIRT_GIC_REDIST].base,
599                                          2, vms->memmap[VIRT_GIC_REDIST].size);
600         } else {
601             qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
602                                  2, vms->memmap[VIRT_GIC_DIST].base,
603                                  2, vms->memmap[VIRT_GIC_DIST].size,
604                                  2, vms->memmap[VIRT_GIC_REDIST].base,
605                                  2, vms->memmap[VIRT_GIC_REDIST].size,
606                                  2, vms->memmap[VIRT_HIGH_GIC_REDIST2].base,
607                                  2, vms->memmap[VIRT_HIGH_GIC_REDIST2].size);
608         }
609 
610         if (vms->virt) {
611             qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
612                                    GIC_FDT_IRQ_TYPE_PPI,
613                                    INTID_TO_PPI(ARCH_GIC_MAINT_IRQ),
614                                    GIC_FDT_IRQ_FLAGS_LEVEL_HI);
615         }
616     } else {
617         /* 'cortex-a15-gic' means 'GIC v2' */
618         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
619                                 "arm,cortex-a15-gic");
620         if (!vms->virt) {
621             qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
622                                          2, vms->memmap[VIRT_GIC_DIST].base,
623                                          2, vms->memmap[VIRT_GIC_DIST].size,
624                                          2, vms->memmap[VIRT_GIC_CPU].base,
625                                          2, vms->memmap[VIRT_GIC_CPU].size);
626         } else {
627             qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
628                                          2, vms->memmap[VIRT_GIC_DIST].base,
629                                          2, vms->memmap[VIRT_GIC_DIST].size,
630                                          2, vms->memmap[VIRT_GIC_CPU].base,
631                                          2, vms->memmap[VIRT_GIC_CPU].size,
632                                          2, vms->memmap[VIRT_GIC_HYP].base,
633                                          2, vms->memmap[VIRT_GIC_HYP].size,
634                                          2, vms->memmap[VIRT_GIC_VCPU].base,
635                                          2, vms->memmap[VIRT_GIC_VCPU].size);
636             qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
637                                    GIC_FDT_IRQ_TYPE_PPI,
638                                    INTID_TO_PPI(ARCH_GIC_MAINT_IRQ),
639                                    GIC_FDT_IRQ_FLAGS_LEVEL_HI);
640         }
641     }
642 
643     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", vms->gic_phandle);
644     g_free(nodename);
645 }
646 
647 static void fdt_add_pmu_nodes(const VirtMachineState *vms)
648 {
649     ARMCPU *armcpu = ARM_CPU(first_cpu);
650     uint32_t irqflags = GIC_FDT_IRQ_FLAGS_LEVEL_HI;
651     MachineState *ms = MACHINE(vms);
652 
653     if (!arm_feature(&armcpu->env, ARM_FEATURE_PMU)) {
654         assert(!object_property_get_bool(OBJECT(armcpu), "pmu", NULL));
655         return;
656     }
657 
658     if (vms->gic_version == VIRT_GIC_VERSION_2) {
659         irqflags = deposit32(irqflags, GIC_FDT_IRQ_PPI_CPU_START,
660                              GIC_FDT_IRQ_PPI_CPU_WIDTH,
661                              (1 << MACHINE(vms)->smp.cpus) - 1);
662     }
663 
664     qemu_fdt_add_subnode(ms->fdt, "/pmu");
665     if (arm_feature(&armcpu->env, ARM_FEATURE_V8)) {
666         const char compat[] = "arm,armv8-pmuv3";
667         qemu_fdt_setprop(ms->fdt, "/pmu", "compatible",
668                          compat, sizeof(compat));
669         qemu_fdt_setprop_cells(ms->fdt, "/pmu", "interrupts",
670                                GIC_FDT_IRQ_TYPE_PPI,
671                                INTID_TO_PPI(VIRTUAL_PMU_IRQ), irqflags);
672     }
673 }
674 
675 static inline DeviceState *create_acpi_ged(VirtMachineState *vms)
676 {
677     DeviceState *dev;
678     MachineState *ms = MACHINE(vms);
679     int irq = vms->irqmap[VIRT_ACPI_GED];
680     uint32_t event = ACPI_GED_PWR_DOWN_EVT;
681 
682     if (ms->ram_slots) {
683         event |= ACPI_GED_MEM_HOTPLUG_EVT;
684     }
685 
686     if (ms->nvdimms_state->is_enabled) {
687         event |= ACPI_GED_NVDIMM_HOTPLUG_EVT;
688     }
689 
690     dev = qdev_new(TYPE_ACPI_GED);
691     qdev_prop_set_uint32(dev, "ged-event", event);
692     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
693 
694     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VIRT_ACPI_GED].base);
695     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 1, vms->memmap[VIRT_PCDIMM_ACPI].base);
696     sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, qdev_get_gpio_in(vms->gic, irq));
697 
698     return dev;
699 }
700 
701 static void create_its(VirtMachineState *vms)
702 {
703     const char *itsclass = its_class_name();
704     DeviceState *dev;
705 
706     if (!strcmp(itsclass, "arm-gicv3-its")) {
707         if (!vms->tcg_its) {
708             itsclass = NULL;
709         }
710     }
711 
712     if (!itsclass) {
713         /* Do nothing if not supported */
714         return;
715     }
716 
717     dev = qdev_new(itsclass);
718 
719     object_property_set_link(OBJECT(dev), "parent-gicv3", OBJECT(vms->gic),
720                              &error_abort);
721     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
722     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VIRT_GIC_ITS].base);
723 
724     fdt_add_its_gic_node(vms);
725     vms->msi_controller = VIRT_MSI_CTRL_ITS;
726 }
727 
728 static void create_v2m(VirtMachineState *vms)
729 {
730     int i;
731     int irq = vms->irqmap[VIRT_GIC_V2M];
732     DeviceState *dev;
733 
734     dev = qdev_new("arm-gicv2m");
735     qdev_prop_set_uint32(dev, "base-spi", irq);
736     qdev_prop_set_uint32(dev, "num-spi", NUM_GICV2M_SPIS);
737     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
738     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VIRT_GIC_V2M].base);
739 
740     for (i = 0; i < NUM_GICV2M_SPIS; i++) {
741         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
742                            qdev_get_gpio_in(vms->gic, irq + i));
743     }
744 
745     fdt_add_v2m_gic_node(vms);
746     vms->msi_controller = VIRT_MSI_CTRL_GICV2M;
747 }
748 
749 /*
750  * If the CPU has FEAT_NMI, then turn on the NMI support in the GICv3 too.
751  * It's permitted to have a configuration with NMI in the CPU (and thus the
752  * GICv3 CPU interface) but not in the distributor/redistributors, but it's
753  * not very useful.
754  */
755 static bool gicv3_nmi_present(VirtMachineState *vms)
756 {
757     ARMCPU *cpu = ARM_CPU(qemu_get_cpu(0));
758 
759     return tcg_enabled() && cpu_isar_feature(aa64_nmi, cpu) &&
760            (vms->gic_version != VIRT_GIC_VERSION_2);
761 }
762 
763 static void create_gic(VirtMachineState *vms, MemoryRegion *mem)
764 {
765     MachineState *ms = MACHINE(vms);
766     /* We create a standalone GIC */
767     SysBusDevice *gicbusdev;
768     const char *gictype;
769     int i;
770     unsigned int smp_cpus = ms->smp.cpus;
771     uint32_t nb_redist_regions = 0;
772     int revision;
773 
774     if (vms->gic_version == VIRT_GIC_VERSION_2) {
775         gictype = gic_class_name();
776     } else {
777         gictype = gicv3_class_name();
778     }
779 
780     switch (vms->gic_version) {
781     case VIRT_GIC_VERSION_2:
782         revision = 2;
783         break;
784     case VIRT_GIC_VERSION_3:
785         revision = 3;
786         break;
787     case VIRT_GIC_VERSION_4:
788         revision = 4;
789         break;
790     default:
791         g_assert_not_reached();
792     }
793     vms->gic = qdev_new(gictype);
794     qdev_prop_set_uint32(vms->gic, "revision", revision);
795     qdev_prop_set_uint32(vms->gic, "num-cpu", smp_cpus);
796     /* Note that the num-irq property counts both internal and external
797      * interrupts; there are always 32 of the former (mandated by GIC spec).
798      */
799     qdev_prop_set_uint32(vms->gic, "num-irq", NUM_IRQS + 32);
800     if (!kvm_irqchip_in_kernel()) {
801         qdev_prop_set_bit(vms->gic, "has-security-extensions", vms->secure);
802     }
803 
804     if (vms->gic_version != VIRT_GIC_VERSION_2) {
805         QList *redist_region_count;
806         uint32_t redist0_capacity = virt_redist_capacity(vms, VIRT_GIC_REDIST);
807         uint32_t redist0_count = MIN(smp_cpus, redist0_capacity);
808 
809         nb_redist_regions = virt_gicv3_redist_region_count(vms);
810 
811         redist_region_count = qlist_new();
812         qlist_append_int(redist_region_count, redist0_count);
813         if (nb_redist_regions == 2) {
814             uint32_t redist1_capacity =
815                 virt_redist_capacity(vms, VIRT_HIGH_GIC_REDIST2);
816 
817             qlist_append_int(redist_region_count,
818                 MIN(smp_cpus - redist0_count, redist1_capacity));
819         }
820         qdev_prop_set_array(vms->gic, "redist-region-count",
821                             redist_region_count);
822 
823         if (!kvm_irqchip_in_kernel()) {
824             if (vms->tcg_its) {
825                 object_property_set_link(OBJECT(vms->gic), "sysmem",
826                                          OBJECT(mem), &error_fatal);
827                 qdev_prop_set_bit(vms->gic, "has-lpi", true);
828             }
829         }
830     } else {
831         if (!kvm_irqchip_in_kernel()) {
832             qdev_prop_set_bit(vms->gic, "has-virtualization-extensions",
833                               vms->virt);
834         }
835     }
836 
837     if (gicv3_nmi_present(vms)) {
838         qdev_prop_set_bit(vms->gic, "has-nmi", true);
839     }
840 
841     gicbusdev = SYS_BUS_DEVICE(vms->gic);
842     sysbus_realize_and_unref(gicbusdev, &error_fatal);
843     sysbus_mmio_map(gicbusdev, 0, vms->memmap[VIRT_GIC_DIST].base);
844     if (vms->gic_version != VIRT_GIC_VERSION_2) {
845         sysbus_mmio_map(gicbusdev, 1, vms->memmap[VIRT_GIC_REDIST].base);
846         if (nb_redist_regions == 2) {
847             sysbus_mmio_map(gicbusdev, 2,
848                             vms->memmap[VIRT_HIGH_GIC_REDIST2].base);
849         }
850     } else {
851         sysbus_mmio_map(gicbusdev, 1, vms->memmap[VIRT_GIC_CPU].base);
852         if (vms->virt) {
853             sysbus_mmio_map(gicbusdev, 2, vms->memmap[VIRT_GIC_HYP].base);
854             sysbus_mmio_map(gicbusdev, 3, vms->memmap[VIRT_GIC_VCPU].base);
855         }
856     }
857 
858     /* Wire the outputs from each CPU's generic timer and the GICv3
859      * maintenance interrupt signal to the appropriate GIC PPI inputs,
860      * and the GIC's IRQ/FIQ/VIRQ/VFIQ/NMI/VINMI interrupt outputs to the
861      * CPU's inputs.
862      */
863     for (i = 0; i < smp_cpus; i++) {
864         DeviceState *cpudev = DEVICE(qemu_get_cpu(i));
865         int intidbase = NUM_IRQS + i * GIC_INTERNAL;
866         /* Mapping from the output timer irq lines from the CPU to the
867          * GIC PPI inputs we use for the virt board.
868          */
869         const int timer_irq[] = {
870             [GTIMER_PHYS] = ARCH_TIMER_NS_EL1_IRQ,
871             [GTIMER_VIRT] = ARCH_TIMER_VIRT_IRQ,
872             [GTIMER_HYP]  = ARCH_TIMER_NS_EL2_IRQ,
873             [GTIMER_SEC]  = ARCH_TIMER_S_EL1_IRQ,
874             [GTIMER_HYPVIRT] = ARCH_TIMER_NS_EL2_VIRT_IRQ,
875         };
876 
877         for (unsigned irq = 0; irq < ARRAY_SIZE(timer_irq); irq++) {
878             qdev_connect_gpio_out(cpudev, irq,
879                                   qdev_get_gpio_in(vms->gic,
880                                                    intidbase + timer_irq[irq]));
881         }
882 
883         if (vms->gic_version != VIRT_GIC_VERSION_2) {
884             qemu_irq irq = qdev_get_gpio_in(vms->gic,
885                                             intidbase + ARCH_GIC_MAINT_IRQ);
886             qdev_connect_gpio_out_named(cpudev, "gicv3-maintenance-interrupt",
887                                         0, irq);
888         } else if (vms->virt) {
889             qemu_irq irq = qdev_get_gpio_in(vms->gic,
890                                             intidbase + ARCH_GIC_MAINT_IRQ);
891             sysbus_connect_irq(gicbusdev, i + 4 * smp_cpus, irq);
892         }
893 
894         qdev_connect_gpio_out_named(cpudev, "pmu-interrupt", 0,
895                                     qdev_get_gpio_in(vms->gic, intidbase
896                                                      + VIRTUAL_PMU_IRQ));
897 
898         sysbus_connect_irq(gicbusdev, i, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ));
899         sysbus_connect_irq(gicbusdev, i + smp_cpus,
900                            qdev_get_gpio_in(cpudev, ARM_CPU_FIQ));
901         sysbus_connect_irq(gicbusdev, i + 2 * smp_cpus,
902                            qdev_get_gpio_in(cpudev, ARM_CPU_VIRQ));
903         sysbus_connect_irq(gicbusdev, i + 3 * smp_cpus,
904                            qdev_get_gpio_in(cpudev, ARM_CPU_VFIQ));
905 
906         if (vms->gic_version != VIRT_GIC_VERSION_2) {
907             sysbus_connect_irq(gicbusdev, i + 4 * smp_cpus,
908                                qdev_get_gpio_in(cpudev, ARM_CPU_NMI));
909             sysbus_connect_irq(gicbusdev, i + 5 * smp_cpus,
910                                qdev_get_gpio_in(cpudev, ARM_CPU_VINMI));
911         }
912     }
913 
914     fdt_add_gic_node(vms);
915 
916     if (vms->gic_version != VIRT_GIC_VERSION_2 && vms->its) {
917         create_its(vms);
918     } else if (vms->gic_version == VIRT_GIC_VERSION_2) {
919         create_v2m(vms);
920     }
921 }
922 
923 static void create_uart(const VirtMachineState *vms, int uart,
924                         MemoryRegion *mem, Chardev *chr, bool secure)
925 {
926     char *nodename;
927     hwaddr base = vms->memmap[uart].base;
928     hwaddr size = vms->memmap[uart].size;
929     int irq = vms->irqmap[uart];
930     const char compat[] = "arm,pl011\0arm,primecell";
931     const char clocknames[] = "uartclk\0apb_pclk";
932     DeviceState *dev = qdev_new(TYPE_PL011);
933     SysBusDevice *s = SYS_BUS_DEVICE(dev);
934     MachineState *ms = MACHINE(vms);
935 
936     qdev_prop_set_chr(dev, "chardev", chr);
937     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
938     memory_region_add_subregion(mem, base,
939                                 sysbus_mmio_get_region(s, 0));
940     sysbus_connect_irq(s, 0, qdev_get_gpio_in(vms->gic, irq));
941 
942     nodename = g_strdup_printf("/pl011@%" PRIx64, base);
943     qemu_fdt_add_subnode(ms->fdt, nodename);
944     /* Note that we can't use setprop_string because of the embedded NUL */
945     qemu_fdt_setprop(ms->fdt, nodename, "compatible",
946                          compat, sizeof(compat));
947     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
948                                      2, base, 2, size);
949     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
950                                GIC_FDT_IRQ_TYPE_SPI, irq,
951                                GIC_FDT_IRQ_FLAGS_LEVEL_HI);
952     qemu_fdt_setprop_cells(ms->fdt, nodename, "clocks",
953                                vms->clock_phandle, vms->clock_phandle);
954     qemu_fdt_setprop(ms->fdt, nodename, "clock-names",
955                          clocknames, sizeof(clocknames));
956 
957     if (uart == VIRT_UART0) {
958         qemu_fdt_setprop_string(ms->fdt, "/chosen", "stdout-path", nodename);
959         qemu_fdt_setprop_string(ms->fdt, "/aliases", "serial0", nodename);
960     } else {
961         qemu_fdt_setprop_string(ms->fdt, "/aliases", "serial1", nodename);
962     }
963     if (secure) {
964         /* Mark as not usable by the normal world */
965         qemu_fdt_setprop_string(ms->fdt, nodename, "status", "disabled");
966         qemu_fdt_setprop_string(ms->fdt, nodename, "secure-status", "okay");
967 
968         qemu_fdt_setprop_string(ms->fdt, "/secure-chosen", "stdout-path",
969                                 nodename);
970     }
971 
972     g_free(nodename);
973 }
974 
975 static void create_rtc(const VirtMachineState *vms)
976 {
977     char *nodename;
978     hwaddr base = vms->memmap[VIRT_RTC].base;
979     hwaddr size = vms->memmap[VIRT_RTC].size;
980     int irq = vms->irqmap[VIRT_RTC];
981     const char compat[] = "arm,pl031\0arm,primecell";
982     MachineState *ms = MACHINE(vms);
983 
984     sysbus_create_simple("pl031", base, qdev_get_gpio_in(vms->gic, irq));
985 
986     nodename = g_strdup_printf("/pl031@%" PRIx64, base);
987     qemu_fdt_add_subnode(ms->fdt, nodename);
988     qemu_fdt_setprop(ms->fdt, nodename, "compatible", compat, sizeof(compat));
989     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
990                                  2, base, 2, size);
991     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
992                            GIC_FDT_IRQ_TYPE_SPI, irq,
993                            GIC_FDT_IRQ_FLAGS_LEVEL_HI);
994     qemu_fdt_setprop_cell(ms->fdt, nodename, "clocks", vms->clock_phandle);
995     qemu_fdt_setprop_string(ms->fdt, nodename, "clock-names", "apb_pclk");
996     g_free(nodename);
997 }
998 
999 static DeviceState *gpio_key_dev;
1000 static void virt_powerdown_req(Notifier *n, void *opaque)
1001 {
1002     VirtMachineState *s = container_of(n, VirtMachineState, powerdown_notifier);
1003 
1004     if (s->acpi_dev) {
1005         acpi_send_event(s->acpi_dev, ACPI_POWER_DOWN_STATUS);
1006     } else {
1007         /* use gpio Pin for power button event */
1008         qemu_set_irq(qdev_get_gpio_in(gpio_key_dev, 0), 1);
1009     }
1010 }
1011 
1012 static void create_gpio_keys(char *fdt, DeviceState *pl061_dev,
1013                              uint32_t phandle)
1014 {
1015     gpio_key_dev = sysbus_create_simple("gpio-key", -1,
1016                                         qdev_get_gpio_in(pl061_dev,
1017                                                          GPIO_PIN_POWER_BUTTON));
1018 
1019     qemu_fdt_add_subnode(fdt, "/gpio-keys");
1020     qemu_fdt_setprop_string(fdt, "/gpio-keys", "compatible", "gpio-keys");
1021 
1022     qemu_fdt_add_subnode(fdt, "/gpio-keys/poweroff");
1023     qemu_fdt_setprop_string(fdt, "/gpio-keys/poweroff",
1024                             "label", "GPIO Key Poweroff");
1025     qemu_fdt_setprop_cell(fdt, "/gpio-keys/poweroff", "linux,code",
1026                           KEY_POWER);
1027     qemu_fdt_setprop_cells(fdt, "/gpio-keys/poweroff",
1028                            "gpios", phandle, GPIO_PIN_POWER_BUTTON, 0);
1029 }
1030 
1031 #define SECURE_GPIO_POWEROFF 0
1032 #define SECURE_GPIO_RESET    1
1033 
1034 static void create_secure_gpio_pwr(char *fdt, DeviceState *pl061_dev,
1035                                    uint32_t phandle)
1036 {
1037     DeviceState *gpio_pwr_dev;
1038 
1039     /* gpio-pwr */
1040     gpio_pwr_dev = sysbus_create_simple("gpio-pwr", -1, NULL);
1041 
1042     /* connect secure pl061 to gpio-pwr */
1043     qdev_connect_gpio_out(pl061_dev, SECURE_GPIO_RESET,
1044                           qdev_get_gpio_in_named(gpio_pwr_dev, "reset", 0));
1045     qdev_connect_gpio_out(pl061_dev, SECURE_GPIO_POWEROFF,
1046                           qdev_get_gpio_in_named(gpio_pwr_dev, "shutdown", 0));
1047 
1048     qemu_fdt_add_subnode(fdt, "/gpio-poweroff");
1049     qemu_fdt_setprop_string(fdt, "/gpio-poweroff", "compatible",
1050                             "gpio-poweroff");
1051     qemu_fdt_setprop_cells(fdt, "/gpio-poweroff",
1052                            "gpios", phandle, SECURE_GPIO_POWEROFF, 0);
1053     qemu_fdt_setprop_string(fdt, "/gpio-poweroff", "status", "disabled");
1054     qemu_fdt_setprop_string(fdt, "/gpio-poweroff", "secure-status",
1055                             "okay");
1056 
1057     qemu_fdt_add_subnode(fdt, "/gpio-restart");
1058     qemu_fdt_setprop_string(fdt, "/gpio-restart", "compatible",
1059                             "gpio-restart");
1060     qemu_fdt_setprop_cells(fdt, "/gpio-restart",
1061                            "gpios", phandle, SECURE_GPIO_RESET, 0);
1062     qemu_fdt_setprop_string(fdt, "/gpio-restart", "status", "disabled");
1063     qemu_fdt_setprop_string(fdt, "/gpio-restart", "secure-status",
1064                             "okay");
1065 }
1066 
1067 static void create_gpio_devices(const VirtMachineState *vms, int gpio,
1068                                 MemoryRegion *mem)
1069 {
1070     char *nodename;
1071     DeviceState *pl061_dev;
1072     hwaddr base = vms->memmap[gpio].base;
1073     hwaddr size = vms->memmap[gpio].size;
1074     int irq = vms->irqmap[gpio];
1075     const char compat[] = "arm,pl061\0arm,primecell";
1076     SysBusDevice *s;
1077     MachineState *ms = MACHINE(vms);
1078 
1079     pl061_dev = qdev_new("pl061");
1080     /* Pull lines down to 0 if not driven by the PL061 */
1081     qdev_prop_set_uint32(pl061_dev, "pullups", 0);
1082     qdev_prop_set_uint32(pl061_dev, "pulldowns", 0xff);
1083     s = SYS_BUS_DEVICE(pl061_dev);
1084     sysbus_realize_and_unref(s, &error_fatal);
1085     memory_region_add_subregion(mem, base, sysbus_mmio_get_region(s, 0));
1086     sysbus_connect_irq(s, 0, qdev_get_gpio_in(vms->gic, irq));
1087 
1088     uint32_t phandle = qemu_fdt_alloc_phandle(ms->fdt);
1089     nodename = g_strdup_printf("/pl061@%" PRIx64, base);
1090     qemu_fdt_add_subnode(ms->fdt, nodename);
1091     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1092                                  2, base, 2, size);
1093     qemu_fdt_setprop(ms->fdt, nodename, "compatible", compat, sizeof(compat));
1094     qemu_fdt_setprop_cell(ms->fdt, nodename, "#gpio-cells", 2);
1095     qemu_fdt_setprop(ms->fdt, nodename, "gpio-controller", NULL, 0);
1096     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
1097                            GIC_FDT_IRQ_TYPE_SPI, irq,
1098                            GIC_FDT_IRQ_FLAGS_LEVEL_HI);
1099     qemu_fdt_setprop_cell(ms->fdt, nodename, "clocks", vms->clock_phandle);
1100     qemu_fdt_setprop_string(ms->fdt, nodename, "clock-names", "apb_pclk");
1101     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", phandle);
1102 
1103     if (gpio != VIRT_GPIO) {
1104         /* Mark as not usable by the normal world */
1105         qemu_fdt_setprop_string(ms->fdt, nodename, "status", "disabled");
1106         qemu_fdt_setprop_string(ms->fdt, nodename, "secure-status", "okay");
1107     }
1108     g_free(nodename);
1109 
1110     /* Child gpio devices */
1111     if (gpio == VIRT_GPIO) {
1112         create_gpio_keys(ms->fdt, pl061_dev, phandle);
1113     } else {
1114         create_secure_gpio_pwr(ms->fdt, pl061_dev, phandle);
1115     }
1116 }
1117 
1118 static void create_virtio_devices(const VirtMachineState *vms)
1119 {
1120     int i;
1121     hwaddr size = vms->memmap[VIRT_MMIO].size;
1122     MachineState *ms = MACHINE(vms);
1123 
1124     /* We create the transports in forwards order. Since qbus_realize()
1125      * prepends (not appends) new child buses, the incrementing loop below will
1126      * create a list of virtio-mmio buses with decreasing base addresses.
1127      *
1128      * When a -device option is processed from the command line,
1129      * qbus_find_recursive() picks the next free virtio-mmio bus in forwards
1130      * order. The upshot is that -device options in increasing command line
1131      * order are mapped to virtio-mmio buses with decreasing base addresses.
1132      *
1133      * When this code was originally written, that arrangement ensured that the
1134      * guest Linux kernel would give the lowest "name" (/dev/vda, eth0, etc) to
1135      * the first -device on the command line. (The end-to-end order is a
1136      * function of this loop, qbus_realize(), qbus_find_recursive(), and the
1137      * guest kernel's name-to-address assignment strategy.)
1138      *
1139      * Meanwhile, the kernel's traversal seems to have been reversed; see eg.
1140      * the message, if not necessarily the code, of commit 70161ff336.
1141      * Therefore the loop now establishes the inverse of the original intent.
1142      *
1143      * Unfortunately, we can't counteract the kernel change by reversing the
1144      * loop; it would break existing command lines.
1145      *
1146      * In any case, the kernel makes no guarantee about the stability of
1147      * enumeration order of virtio devices (as demonstrated by it changing
1148      * between kernel versions). For reliable and stable identification
1149      * of disks users must use UUIDs or similar mechanisms.
1150      */
1151     for (i = 0; i < NUM_VIRTIO_TRANSPORTS; i++) {
1152         int irq = vms->irqmap[VIRT_MMIO] + i;
1153         hwaddr base = vms->memmap[VIRT_MMIO].base + i * size;
1154 
1155         sysbus_create_simple("virtio-mmio", base,
1156                              qdev_get_gpio_in(vms->gic, irq));
1157     }
1158 
1159     /* We add dtb nodes in reverse order so that they appear in the finished
1160      * device tree lowest address first.
1161      *
1162      * Note that this mapping is independent of the loop above. The previous
1163      * loop influences virtio device to virtio transport assignment, whereas
1164      * this loop controls how virtio transports are laid out in the dtb.
1165      */
1166     for (i = NUM_VIRTIO_TRANSPORTS - 1; i >= 0; i--) {
1167         char *nodename;
1168         int irq = vms->irqmap[VIRT_MMIO] + i;
1169         hwaddr base = vms->memmap[VIRT_MMIO].base + i * size;
1170 
1171         nodename = g_strdup_printf("/virtio_mmio@%" PRIx64, base);
1172         qemu_fdt_add_subnode(ms->fdt, nodename);
1173         qemu_fdt_setprop_string(ms->fdt, nodename,
1174                                 "compatible", "virtio,mmio");
1175         qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1176                                      2, base, 2, size);
1177         qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
1178                                GIC_FDT_IRQ_TYPE_SPI, irq,
1179                                GIC_FDT_IRQ_FLAGS_EDGE_LO_HI);
1180         qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
1181         g_free(nodename);
1182     }
1183 }
1184 
1185 #define VIRT_FLASH_SECTOR_SIZE (256 * KiB)
1186 
1187 static PFlashCFI01 *virt_flash_create1(VirtMachineState *vms,
1188                                         const char *name,
1189                                         const char *alias_prop_name)
1190 {
1191     /*
1192      * Create a single flash device.  We use the same parameters as
1193      * the flash devices on the Versatile Express board.
1194      */
1195     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI01);
1196 
1197     qdev_prop_set_uint64(dev, "sector-length", VIRT_FLASH_SECTOR_SIZE);
1198     qdev_prop_set_uint8(dev, "width", 4);
1199     qdev_prop_set_uint8(dev, "device-width", 2);
1200     qdev_prop_set_bit(dev, "big-endian", false);
1201     qdev_prop_set_uint16(dev, "id0", 0x89);
1202     qdev_prop_set_uint16(dev, "id1", 0x18);
1203     qdev_prop_set_uint16(dev, "id2", 0x00);
1204     qdev_prop_set_uint16(dev, "id3", 0x00);
1205     qdev_prop_set_string(dev, "name", name);
1206     object_property_add_child(OBJECT(vms), name, OBJECT(dev));
1207     object_property_add_alias(OBJECT(vms), alias_prop_name,
1208                               OBJECT(dev), "drive");
1209     return PFLASH_CFI01(dev);
1210 }
1211 
1212 static void virt_flash_create(VirtMachineState *vms)
1213 {
1214     vms->flash[0] = virt_flash_create1(vms, "virt.flash0", "pflash0");
1215     vms->flash[1] = virt_flash_create1(vms, "virt.flash1", "pflash1");
1216 }
1217 
1218 static void virt_flash_map1(PFlashCFI01 *flash,
1219                             hwaddr base, hwaddr size,
1220                             MemoryRegion *sysmem)
1221 {
1222     DeviceState *dev = DEVICE(flash);
1223 
1224     assert(QEMU_IS_ALIGNED(size, VIRT_FLASH_SECTOR_SIZE));
1225     assert(size / VIRT_FLASH_SECTOR_SIZE <= UINT32_MAX);
1226     qdev_prop_set_uint32(dev, "num-blocks", size / VIRT_FLASH_SECTOR_SIZE);
1227     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1228 
1229     memory_region_add_subregion(sysmem, base,
1230                                 sysbus_mmio_get_region(SYS_BUS_DEVICE(dev),
1231                                                        0));
1232 }
1233 
1234 static void virt_flash_map(VirtMachineState *vms,
1235                            MemoryRegion *sysmem,
1236                            MemoryRegion *secure_sysmem)
1237 {
1238     /*
1239      * Map two flash devices to fill the VIRT_FLASH space in the memmap.
1240      * sysmem is the system memory space. secure_sysmem is the secure view
1241      * of the system, and the first flash device should be made visible only
1242      * there. The second flash device is visible to both secure and nonsecure.
1243      * If sysmem == secure_sysmem this means there is no separate Secure
1244      * address space and both flash devices are generally visible.
1245      */
1246     hwaddr flashsize = vms->memmap[VIRT_FLASH].size / 2;
1247     hwaddr flashbase = vms->memmap[VIRT_FLASH].base;
1248 
1249     virt_flash_map1(vms->flash[0], flashbase, flashsize,
1250                     secure_sysmem);
1251     virt_flash_map1(vms->flash[1], flashbase + flashsize, flashsize,
1252                     sysmem);
1253 }
1254 
1255 static void virt_flash_fdt(VirtMachineState *vms,
1256                            MemoryRegion *sysmem,
1257                            MemoryRegion *secure_sysmem)
1258 {
1259     hwaddr flashsize = vms->memmap[VIRT_FLASH].size / 2;
1260     hwaddr flashbase = vms->memmap[VIRT_FLASH].base;
1261     MachineState *ms = MACHINE(vms);
1262     char *nodename;
1263 
1264     if (sysmem == secure_sysmem) {
1265         /* Report both flash devices as a single node in the DT */
1266         nodename = g_strdup_printf("/flash@%" PRIx64, flashbase);
1267         qemu_fdt_add_subnode(ms->fdt, nodename);
1268         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "cfi-flash");
1269         qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1270                                      2, flashbase, 2, flashsize,
1271                                      2, flashbase + flashsize, 2, flashsize);
1272         qemu_fdt_setprop_cell(ms->fdt, nodename, "bank-width", 4);
1273         g_free(nodename);
1274     } else {
1275         /*
1276          * Report the devices as separate nodes so we can mark one as
1277          * only visible to the secure world.
1278          */
1279         nodename = g_strdup_printf("/secflash@%" PRIx64, flashbase);
1280         qemu_fdt_add_subnode(ms->fdt, nodename);
1281         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "cfi-flash");
1282         qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1283                                      2, flashbase, 2, flashsize);
1284         qemu_fdt_setprop_cell(ms->fdt, nodename, "bank-width", 4);
1285         qemu_fdt_setprop_string(ms->fdt, nodename, "status", "disabled");
1286         qemu_fdt_setprop_string(ms->fdt, nodename, "secure-status", "okay");
1287         g_free(nodename);
1288 
1289         nodename = g_strdup_printf("/flash@%" PRIx64, flashbase + flashsize);
1290         qemu_fdt_add_subnode(ms->fdt, nodename);
1291         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "cfi-flash");
1292         qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1293                                      2, flashbase + flashsize, 2, flashsize);
1294         qemu_fdt_setprop_cell(ms->fdt, nodename, "bank-width", 4);
1295         g_free(nodename);
1296     }
1297 }
1298 
1299 static bool virt_firmware_init(VirtMachineState *vms,
1300                                MemoryRegion *sysmem,
1301                                MemoryRegion *secure_sysmem)
1302 {
1303     int i;
1304     const char *bios_name;
1305     BlockBackend *pflash_blk0;
1306 
1307     /* Map legacy -drive if=pflash to machine properties */
1308     for (i = 0; i < ARRAY_SIZE(vms->flash); i++) {
1309         pflash_cfi01_legacy_drive(vms->flash[i],
1310                                   drive_get(IF_PFLASH, 0, i));
1311     }
1312 
1313     virt_flash_map(vms, sysmem, secure_sysmem);
1314 
1315     pflash_blk0 = pflash_cfi01_get_blk(vms->flash[0]);
1316 
1317     bios_name = MACHINE(vms)->firmware;
1318     if (bios_name) {
1319         char *fname;
1320         MemoryRegion *mr;
1321         int image_size;
1322 
1323         if (pflash_blk0) {
1324             error_report("The contents of the first flash device may be "
1325                          "specified with -bios or with -drive if=pflash... "
1326                          "but you cannot use both options at once");
1327             exit(1);
1328         }
1329 
1330         /* Fall back to -bios */
1331 
1332         fname = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
1333         if (!fname) {
1334             error_report("Could not find ROM image '%s'", bios_name);
1335             exit(1);
1336         }
1337         mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(vms->flash[0]), 0);
1338         image_size = load_image_mr(fname, mr);
1339         g_free(fname);
1340         if (image_size < 0) {
1341             error_report("Could not load ROM image '%s'", bios_name);
1342             exit(1);
1343         }
1344     }
1345 
1346     return pflash_blk0 || bios_name;
1347 }
1348 
1349 static FWCfgState *create_fw_cfg(const VirtMachineState *vms, AddressSpace *as)
1350 {
1351     MachineState *ms = MACHINE(vms);
1352     hwaddr base = vms->memmap[VIRT_FW_CFG].base;
1353     hwaddr size = vms->memmap[VIRT_FW_CFG].size;
1354     FWCfgState *fw_cfg;
1355     char *nodename;
1356 
1357     fw_cfg = fw_cfg_init_mem_wide(base + 8, base, 8, base + 16, as);
1358     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, (uint16_t)ms->smp.cpus);
1359 
1360     nodename = g_strdup_printf("/fw-cfg@%" PRIx64, base);
1361     qemu_fdt_add_subnode(ms->fdt, nodename);
1362     qemu_fdt_setprop_string(ms->fdt, nodename,
1363                             "compatible", "qemu,fw-cfg-mmio");
1364     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1365                                  2, base, 2, size);
1366     qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
1367     g_free(nodename);
1368     return fw_cfg;
1369 }
1370 
1371 static void create_pcie_irq_map(const MachineState *ms,
1372                                 uint32_t gic_phandle,
1373                                 int first_irq, const char *nodename)
1374 {
1375     int devfn, pin;
1376     uint32_t full_irq_map[4 * 4 * 10] = { 0 };
1377     uint32_t *irq_map = full_irq_map;
1378 
1379     for (devfn = 0; devfn <= 0x18; devfn += 0x8) {
1380         for (pin = 0; pin < 4; pin++) {
1381             int irq_type = GIC_FDT_IRQ_TYPE_SPI;
1382             int irq_nr = first_irq + ((pin + PCI_SLOT(devfn)) % PCI_NUM_PINS);
1383             int irq_level = GIC_FDT_IRQ_FLAGS_LEVEL_HI;
1384             int i;
1385 
1386             uint32_t map[] = {
1387                 devfn << 8, 0, 0,                           /* devfn */
1388                 pin + 1,                                    /* PCI pin */
1389                 gic_phandle, 0, 0, irq_type, irq_nr, irq_level }; /* GIC irq */
1390 
1391             /* Convert map to big endian */
1392             for (i = 0; i < 10; i++) {
1393                 irq_map[i] = cpu_to_be32(map[i]);
1394             }
1395             irq_map += 10;
1396         }
1397     }
1398 
1399     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-map",
1400                      full_irq_map, sizeof(full_irq_map));
1401 
1402     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupt-map-mask",
1403                            cpu_to_be16(PCI_DEVFN(3, 0)), /* Slot 3 */
1404                            0, 0,
1405                            0x7           /* PCI irq */);
1406 }
1407 
1408 static void create_smmu(const VirtMachineState *vms,
1409                         PCIBus *bus)
1410 {
1411     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
1412     char *node;
1413     const char compat[] = "arm,smmu-v3";
1414     int irq =  vms->irqmap[VIRT_SMMU];
1415     int i;
1416     hwaddr base = vms->memmap[VIRT_SMMU].base;
1417     hwaddr size = vms->memmap[VIRT_SMMU].size;
1418     const char irq_names[] = "eventq\0priq\0cmdq-sync\0gerror";
1419     DeviceState *dev;
1420     MachineState *ms = MACHINE(vms);
1421 
1422     if (vms->iommu != VIRT_IOMMU_SMMUV3 || !vms->iommu_phandle) {
1423         return;
1424     }
1425 
1426     dev = qdev_new(TYPE_ARM_SMMUV3);
1427 
1428     if (!vmc->no_nested_smmu) {
1429         object_property_set_str(OBJECT(dev), "stage", "nested", &error_fatal);
1430     }
1431     object_property_set_link(OBJECT(dev), "primary-bus", OBJECT(bus),
1432                              &error_abort);
1433     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1434     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);
1435     for (i = 0; i < NUM_SMMU_IRQS; i++) {
1436         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
1437                            qdev_get_gpio_in(vms->gic, irq + i));
1438     }
1439 
1440     node = g_strdup_printf("/smmuv3@%" PRIx64, base);
1441     qemu_fdt_add_subnode(ms->fdt, node);
1442     qemu_fdt_setprop(ms->fdt, node, "compatible", compat, sizeof(compat));
1443     qemu_fdt_setprop_sized_cells(ms->fdt, node, "reg", 2, base, 2, size);
1444 
1445     qemu_fdt_setprop_cells(ms->fdt, node, "interrupts",
1446             GIC_FDT_IRQ_TYPE_SPI, irq    , GIC_FDT_IRQ_FLAGS_EDGE_LO_HI,
1447             GIC_FDT_IRQ_TYPE_SPI, irq + 1, GIC_FDT_IRQ_FLAGS_EDGE_LO_HI,
1448             GIC_FDT_IRQ_TYPE_SPI, irq + 2, GIC_FDT_IRQ_FLAGS_EDGE_LO_HI,
1449             GIC_FDT_IRQ_TYPE_SPI, irq + 3, GIC_FDT_IRQ_FLAGS_EDGE_LO_HI);
1450 
1451     qemu_fdt_setprop(ms->fdt, node, "interrupt-names", irq_names,
1452                      sizeof(irq_names));
1453 
1454     qemu_fdt_setprop(ms->fdt, node, "dma-coherent", NULL, 0);
1455 
1456     qemu_fdt_setprop_cell(ms->fdt, node, "#iommu-cells", 1);
1457 
1458     qemu_fdt_setprop_cell(ms->fdt, node, "phandle", vms->iommu_phandle);
1459     g_free(node);
1460 }
1461 
1462 static void create_virtio_iommu_dt_bindings(VirtMachineState *vms)
1463 {
1464     const char compat[] = "virtio,pci-iommu\0pci1af4,1057";
1465     uint16_t bdf = vms->virtio_iommu_bdf;
1466     MachineState *ms = MACHINE(vms);
1467     char *node;
1468 
1469     vms->iommu_phandle = qemu_fdt_alloc_phandle(ms->fdt);
1470 
1471     node = g_strdup_printf("%s/virtio_iommu@%x,%x", vms->pciehb_nodename,
1472                            PCI_SLOT(bdf), PCI_FUNC(bdf));
1473     qemu_fdt_add_subnode(ms->fdt, node);
1474     qemu_fdt_setprop(ms->fdt, node, "compatible", compat, sizeof(compat));
1475     qemu_fdt_setprop_sized_cells(ms->fdt, node, "reg",
1476                                  1, bdf << 8, 1, 0, 1, 0,
1477                                  1, 0, 1, 0);
1478 
1479     qemu_fdt_setprop_cell(ms->fdt, node, "#iommu-cells", 1);
1480     qemu_fdt_setprop_cell(ms->fdt, node, "phandle", vms->iommu_phandle);
1481     g_free(node);
1482 
1483     qemu_fdt_setprop_cells(ms->fdt, vms->pciehb_nodename, "iommu-map",
1484                            0x0, vms->iommu_phandle, 0x0, bdf,
1485                            bdf + 1, vms->iommu_phandle, bdf + 1, 0xffff - bdf);
1486 }
1487 
1488 static void create_pcie(VirtMachineState *vms)
1489 {
1490     hwaddr base_mmio = vms->memmap[VIRT_PCIE_MMIO].base;
1491     hwaddr size_mmio = vms->memmap[VIRT_PCIE_MMIO].size;
1492     hwaddr base_mmio_high = vms->memmap[VIRT_HIGH_PCIE_MMIO].base;
1493     hwaddr size_mmio_high = vms->memmap[VIRT_HIGH_PCIE_MMIO].size;
1494     hwaddr base_pio = vms->memmap[VIRT_PCIE_PIO].base;
1495     hwaddr size_pio = vms->memmap[VIRT_PCIE_PIO].size;
1496     hwaddr base_ecam, size_ecam;
1497     hwaddr base = base_mmio;
1498     int nr_pcie_buses;
1499     int irq = vms->irqmap[VIRT_PCIE];
1500     MemoryRegion *mmio_alias;
1501     MemoryRegion *mmio_reg;
1502     MemoryRegion *ecam_alias;
1503     MemoryRegion *ecam_reg;
1504     DeviceState *dev;
1505     char *nodename;
1506     int i, ecam_id;
1507     PCIHostState *pci;
1508     MachineState *ms = MACHINE(vms);
1509     MachineClass *mc = MACHINE_GET_CLASS(ms);
1510 
1511     dev = qdev_new(TYPE_GPEX_HOST);
1512     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1513 
1514     ecam_id = VIRT_ECAM_ID(vms->highmem_ecam);
1515     base_ecam = vms->memmap[ecam_id].base;
1516     size_ecam = vms->memmap[ecam_id].size;
1517     nr_pcie_buses = size_ecam / PCIE_MMCFG_SIZE_MIN;
1518     /* Map only the first size_ecam bytes of ECAM space */
1519     ecam_alias = g_new0(MemoryRegion, 1);
1520     ecam_reg = sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 0);
1521     memory_region_init_alias(ecam_alias, OBJECT(dev), "pcie-ecam",
1522                              ecam_reg, 0, size_ecam);
1523     memory_region_add_subregion(get_system_memory(), base_ecam, ecam_alias);
1524 
1525     /* Map the MMIO window into system address space so as to expose
1526      * the section of PCI MMIO space which starts at the same base address
1527      * (ie 1:1 mapping for that part of PCI MMIO space visible through
1528      * the window).
1529      */
1530     mmio_alias = g_new0(MemoryRegion, 1);
1531     mmio_reg = sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 1);
1532     memory_region_init_alias(mmio_alias, OBJECT(dev), "pcie-mmio",
1533                              mmio_reg, base_mmio, size_mmio);
1534     memory_region_add_subregion(get_system_memory(), base_mmio, mmio_alias);
1535 
1536     if (vms->highmem_mmio) {
1537         /* Map high MMIO space */
1538         MemoryRegion *high_mmio_alias = g_new0(MemoryRegion, 1);
1539 
1540         memory_region_init_alias(high_mmio_alias, OBJECT(dev), "pcie-mmio-high",
1541                                  mmio_reg, base_mmio_high, size_mmio_high);
1542         memory_region_add_subregion(get_system_memory(), base_mmio_high,
1543                                     high_mmio_alias);
1544     }
1545 
1546     /* Map IO port space */
1547     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
1548 
1549     for (i = 0; i < GPEX_NUM_IRQS; i++) {
1550         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
1551                            qdev_get_gpio_in(vms->gic, irq + i));
1552         gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
1553     }
1554 
1555     pci = PCI_HOST_BRIDGE(dev);
1556     pci->bypass_iommu = vms->default_bus_bypass_iommu;
1557     vms->bus = pci->bus;
1558     if (vms->bus) {
1559         pci_init_nic_devices(pci->bus, mc->default_nic);
1560     }
1561 
1562     nodename = vms->pciehb_nodename = g_strdup_printf("/pcie@%" PRIx64, base);
1563     qemu_fdt_add_subnode(ms->fdt, nodename);
1564     qemu_fdt_setprop_string(ms->fdt, nodename,
1565                             "compatible", "pci-host-ecam-generic");
1566     qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "pci");
1567     qemu_fdt_setprop_cell(ms->fdt, nodename, "#address-cells", 3);
1568     qemu_fdt_setprop_cell(ms->fdt, nodename, "#size-cells", 2);
1569     qemu_fdt_setprop_cell(ms->fdt, nodename, "linux,pci-domain", 0);
1570     qemu_fdt_setprop_cells(ms->fdt, nodename, "bus-range", 0,
1571                            nr_pcie_buses - 1);
1572     qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
1573 
1574     if (vms->msi_phandle) {
1575         qemu_fdt_setprop_cells(ms->fdt, nodename, "msi-map",
1576                                0, vms->msi_phandle, 0, 0x10000);
1577     }
1578 
1579     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
1580                                  2, base_ecam, 2, size_ecam);
1581 
1582     if (vms->highmem_mmio) {
1583         qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "ranges",
1584                                      1, FDT_PCI_RANGE_IOPORT, 2, 0,
1585                                      2, base_pio, 2, size_pio,
1586                                      1, FDT_PCI_RANGE_MMIO, 2, base_mmio,
1587                                      2, base_mmio, 2, size_mmio,
1588                                      1, FDT_PCI_RANGE_MMIO_64BIT,
1589                                      2, base_mmio_high,
1590                                      2, base_mmio_high, 2, size_mmio_high);
1591     } else {
1592         qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "ranges",
1593                                      1, FDT_PCI_RANGE_IOPORT, 2, 0,
1594                                      2, base_pio, 2, size_pio,
1595                                      1, FDT_PCI_RANGE_MMIO, 2, base_mmio,
1596                                      2, base_mmio, 2, size_mmio);
1597     }
1598 
1599     qemu_fdt_setprop_cell(ms->fdt, nodename, "#interrupt-cells", 1);
1600     create_pcie_irq_map(ms, vms->gic_phandle, irq, nodename);
1601 
1602     if (vms->iommu) {
1603         vms->iommu_phandle = qemu_fdt_alloc_phandle(ms->fdt);
1604 
1605         switch (vms->iommu) {
1606         case VIRT_IOMMU_SMMUV3:
1607             create_smmu(vms, vms->bus);
1608             qemu_fdt_setprop_cells(ms->fdt, nodename, "iommu-map",
1609                                    0x0, vms->iommu_phandle, 0x0, 0x10000);
1610             break;
1611         default:
1612             g_assert_not_reached();
1613         }
1614     }
1615 }
1616 
1617 static void create_platform_bus(VirtMachineState *vms)
1618 {
1619     DeviceState *dev;
1620     SysBusDevice *s;
1621     int i;
1622     MemoryRegion *sysmem = get_system_memory();
1623 
1624     dev = qdev_new(TYPE_PLATFORM_BUS_DEVICE);
1625     dev->id = g_strdup(TYPE_PLATFORM_BUS_DEVICE);
1626     qdev_prop_set_uint32(dev, "num_irqs", PLATFORM_BUS_NUM_IRQS);
1627     qdev_prop_set_uint32(dev, "mmio_size", vms->memmap[VIRT_PLATFORM_BUS].size);
1628     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1629     vms->platform_bus_dev = dev;
1630 
1631     s = SYS_BUS_DEVICE(dev);
1632     for (i = 0; i < PLATFORM_BUS_NUM_IRQS; i++) {
1633         int irq = vms->irqmap[VIRT_PLATFORM_BUS] + i;
1634         sysbus_connect_irq(s, i, qdev_get_gpio_in(vms->gic, irq));
1635     }
1636 
1637     memory_region_add_subregion(sysmem,
1638                                 vms->memmap[VIRT_PLATFORM_BUS].base,
1639                                 sysbus_mmio_get_region(s, 0));
1640 }
1641 
1642 static void create_tag_ram(MemoryRegion *tag_sysmem,
1643                            hwaddr base, hwaddr size,
1644                            const char *name)
1645 {
1646     MemoryRegion *tagram = g_new(MemoryRegion, 1);
1647 
1648     memory_region_init_ram(tagram, NULL, name, size / 32, &error_fatal);
1649     memory_region_add_subregion(tag_sysmem, base / 32, tagram);
1650 }
1651 
1652 static void create_secure_ram(VirtMachineState *vms,
1653                               MemoryRegion *secure_sysmem,
1654                               MemoryRegion *secure_tag_sysmem)
1655 {
1656     MemoryRegion *secram = g_new(MemoryRegion, 1);
1657     char *nodename;
1658     hwaddr base = vms->memmap[VIRT_SECURE_MEM].base;
1659     hwaddr size = vms->memmap[VIRT_SECURE_MEM].size;
1660     MachineState *ms = MACHINE(vms);
1661 
1662     memory_region_init_ram(secram, NULL, "virt.secure-ram", size,
1663                            &error_fatal);
1664     memory_region_add_subregion(secure_sysmem, base, secram);
1665 
1666     nodename = g_strdup_printf("/secram@%" PRIx64, base);
1667     qemu_fdt_add_subnode(ms->fdt, nodename);
1668     qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "memory");
1669     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg", 2, base, 2, size);
1670     qemu_fdt_setprop_string(ms->fdt, nodename, "status", "disabled");
1671     qemu_fdt_setprop_string(ms->fdt, nodename, "secure-status", "okay");
1672 
1673     if (secure_tag_sysmem) {
1674         create_tag_ram(secure_tag_sysmem, base, size, "mach-virt.secure-tag");
1675     }
1676 
1677     g_free(nodename);
1678 }
1679 
1680 static void *machvirt_dtb(const struct arm_boot_info *binfo, int *fdt_size)
1681 {
1682     const VirtMachineState *board = container_of(binfo, VirtMachineState,
1683                                                  bootinfo);
1684     MachineState *ms = MACHINE(board);
1685 
1686 
1687     *fdt_size = board->fdt_size;
1688     return ms->fdt;
1689 }
1690 
1691 static void virt_build_smbios(VirtMachineState *vms)
1692 {
1693     MachineClass *mc = MACHINE_GET_CLASS(vms);
1694     MachineState *ms = MACHINE(vms);
1695     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
1696     uint8_t *smbios_tables, *smbios_anchor;
1697     size_t smbios_tables_len, smbios_anchor_len;
1698     struct smbios_phys_mem_area mem_array;
1699     const char *product = "QEMU Virtual Machine";
1700 
1701     if (kvm_enabled()) {
1702         product = "KVM Virtual Machine";
1703     }
1704 
1705     smbios_set_defaults("QEMU", product,
1706                         vmc->smbios_old_sys_ver ? "1.0" : mc->name);
1707 
1708     /* build the array of physical mem area from base_memmap */
1709     mem_array.address = vms->memmap[VIRT_MEM].base;
1710     mem_array.length = ms->ram_size;
1711 
1712     smbios_get_tables(ms, SMBIOS_ENTRY_POINT_TYPE_64, &mem_array, 1,
1713                       &smbios_tables, &smbios_tables_len,
1714                       &smbios_anchor, &smbios_anchor_len,
1715                       &error_fatal);
1716 
1717     if (smbios_anchor) {
1718         fw_cfg_add_file(vms->fw_cfg, "etc/smbios/smbios-tables",
1719                         smbios_tables, smbios_tables_len);
1720         fw_cfg_add_file(vms->fw_cfg, "etc/smbios/smbios-anchor",
1721                         smbios_anchor, smbios_anchor_len);
1722     }
1723 }
1724 
1725 static
1726 void virt_machine_done(Notifier *notifier, void *data)
1727 {
1728     VirtMachineState *vms = container_of(notifier, VirtMachineState,
1729                                          machine_done);
1730     MachineState *ms = MACHINE(vms);
1731     ARMCPU *cpu = ARM_CPU(first_cpu);
1732     struct arm_boot_info *info = &vms->bootinfo;
1733     AddressSpace *as = arm_boot_address_space(cpu, info);
1734 
1735     /*
1736      * If the user provided a dtb, we assume the dynamic sysbus nodes
1737      * already are integrated there. This corresponds to a use case where
1738      * the dynamic sysbus nodes are complex and their generation is not yet
1739      * supported. In that case the user can take charge of the guest dt
1740      * while qemu takes charge of the qom stuff.
1741      */
1742     if (info->dtb_filename == NULL) {
1743         platform_bus_add_all_fdt_nodes(ms->fdt, "/intc",
1744                                        vms->memmap[VIRT_PLATFORM_BUS].base,
1745                                        vms->memmap[VIRT_PLATFORM_BUS].size,
1746                                        vms->irqmap[VIRT_PLATFORM_BUS]);
1747     }
1748     if (arm_load_dtb(info->dtb_start, info, info->dtb_limit, as, ms) < 0) {
1749         exit(1);
1750     }
1751 
1752     fw_cfg_add_extra_pci_roots(vms->bus, vms->fw_cfg);
1753 
1754     virt_acpi_setup(vms);
1755     virt_build_smbios(vms);
1756 }
1757 
1758 static uint64_t virt_cpu_mp_affinity(VirtMachineState *vms, int idx)
1759 {
1760     uint8_t clustersz = ARM_DEFAULT_CPUS_PER_CLUSTER;
1761     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
1762 
1763     if (!vmc->disallow_affinity_adjustment) {
1764         /* Adjust MPIDR like 64-bit KVM hosts, which incorporate the
1765          * GIC's target-list limitations. 32-bit KVM hosts currently
1766          * always create clusters of 4 CPUs, but that is expected to
1767          * change when they gain support for gicv3. When KVM is enabled
1768          * it will override the changes we make here, therefore our
1769          * purposes are to make TCG consistent (with 64-bit KVM hosts)
1770          * and to improve SGI efficiency.
1771          */
1772         if (vms->gic_version == VIRT_GIC_VERSION_2) {
1773             clustersz = GIC_TARGETLIST_BITS;
1774         } else {
1775             clustersz = GICV3_TARGETLIST_BITS;
1776         }
1777     }
1778     return arm_build_mp_affinity(idx, clustersz);
1779 }
1780 
1781 static inline bool *virt_get_high_memmap_enabled(VirtMachineState *vms,
1782                                                  int index)
1783 {
1784     bool *enabled_array[] = {
1785         &vms->highmem_redists,
1786         &vms->highmem_ecam,
1787         &vms->highmem_mmio,
1788     };
1789 
1790     assert(ARRAY_SIZE(extended_memmap) - VIRT_LOWMEMMAP_LAST ==
1791            ARRAY_SIZE(enabled_array));
1792     assert(index - VIRT_LOWMEMMAP_LAST < ARRAY_SIZE(enabled_array));
1793 
1794     return enabled_array[index - VIRT_LOWMEMMAP_LAST];
1795 }
1796 
1797 static void virt_set_high_memmap(VirtMachineState *vms,
1798                                  hwaddr base, int pa_bits)
1799 {
1800     hwaddr region_base, region_size;
1801     bool *region_enabled, fits;
1802     int i;
1803 
1804     for (i = VIRT_LOWMEMMAP_LAST; i < ARRAY_SIZE(extended_memmap); i++) {
1805         region_enabled = virt_get_high_memmap_enabled(vms, i);
1806         region_base = ROUND_UP(base, extended_memmap[i].size);
1807         region_size = extended_memmap[i].size;
1808 
1809         vms->memmap[i].base = region_base;
1810         vms->memmap[i].size = region_size;
1811 
1812         /*
1813          * Check each device to see if it fits in the PA space,
1814          * moving highest_gpa as we go. For compatibility, move
1815          * highest_gpa for disabled fitting devices as well, if
1816          * the compact layout has been disabled.
1817          *
1818          * For each device that doesn't fit, disable it.
1819          */
1820         fits = (region_base + region_size) <= BIT_ULL(pa_bits);
1821         *region_enabled &= fits;
1822         if (vms->highmem_compact && !*region_enabled) {
1823             continue;
1824         }
1825 
1826         base = region_base + region_size;
1827         if (fits) {
1828             vms->highest_gpa = base - 1;
1829         }
1830     }
1831 }
1832 
1833 static void virt_set_memmap(VirtMachineState *vms, int pa_bits)
1834 {
1835     MachineState *ms = MACHINE(vms);
1836     hwaddr base, device_memory_base, device_memory_size, memtop;
1837     int i;
1838 
1839     vms->memmap = extended_memmap;
1840 
1841     for (i = 0; i < ARRAY_SIZE(base_memmap); i++) {
1842         vms->memmap[i] = base_memmap[i];
1843     }
1844 
1845     if (ms->ram_slots > ACPI_MAX_RAM_SLOTS) {
1846         error_report("unsupported number of memory slots: %"PRIu64,
1847                      ms->ram_slots);
1848         exit(EXIT_FAILURE);
1849     }
1850 
1851     /*
1852      * !highmem is exactly the same as limiting the PA space to 32bit,
1853      * irrespective of the underlying capabilities of the HW.
1854      */
1855     if (!vms->highmem) {
1856         pa_bits = 32;
1857     }
1858 
1859     /*
1860      * We compute the base of the high IO region depending on the
1861      * amount of initial and device memory. The device memory start/size
1862      * is aligned on 1GiB. We never put the high IO region below 256GiB
1863      * so that if maxram_size is < 255GiB we keep the legacy memory map.
1864      * The device region size assumes 1GiB page max alignment per slot.
1865      */
1866     device_memory_base =
1867         ROUND_UP(vms->memmap[VIRT_MEM].base + ms->ram_size, GiB);
1868     device_memory_size = ms->maxram_size - ms->ram_size + ms->ram_slots * GiB;
1869 
1870     /* Base address of the high IO region */
1871     memtop = base = device_memory_base + ROUND_UP(device_memory_size, GiB);
1872     if (memtop > BIT_ULL(pa_bits)) {
1873         error_report("Addressing limited to %d bits, but memory exceeds it by %llu bytes",
1874                      pa_bits, memtop - BIT_ULL(pa_bits));
1875         exit(EXIT_FAILURE);
1876     }
1877     if (base < device_memory_base) {
1878         error_report("maxmem/slots too huge");
1879         exit(EXIT_FAILURE);
1880     }
1881     if (base < vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES) {
1882         base = vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES;
1883     }
1884 
1885     /* We know for sure that at least the memory fits in the PA space */
1886     vms->highest_gpa = memtop - 1;
1887 
1888     virt_set_high_memmap(vms, base, pa_bits);
1889 
1890     if (device_memory_size > 0) {
1891         machine_memory_devices_init(ms, device_memory_base, device_memory_size);
1892     }
1893 }
1894 
1895 static VirtGICType finalize_gic_version_do(const char *accel_name,
1896                                            VirtGICType gic_version,
1897                                            int gics_supported,
1898                                            unsigned int max_cpus)
1899 {
1900     /* Convert host/max/nosel to GIC version number */
1901     switch (gic_version) {
1902     case VIRT_GIC_VERSION_HOST:
1903         if (!kvm_enabled()) {
1904             error_report("gic-version=host requires KVM");
1905             exit(1);
1906         }
1907 
1908         /* For KVM, gic-version=host means gic-version=max */
1909         return finalize_gic_version_do(accel_name, VIRT_GIC_VERSION_MAX,
1910                                        gics_supported, max_cpus);
1911     case VIRT_GIC_VERSION_MAX:
1912         if (gics_supported & VIRT_GIC_VERSION_4_MASK) {
1913             gic_version = VIRT_GIC_VERSION_4;
1914         } else if (gics_supported & VIRT_GIC_VERSION_3_MASK) {
1915             gic_version = VIRT_GIC_VERSION_3;
1916         } else {
1917             gic_version = VIRT_GIC_VERSION_2;
1918         }
1919         break;
1920     case VIRT_GIC_VERSION_NOSEL:
1921         if ((gics_supported & VIRT_GIC_VERSION_2_MASK) &&
1922             max_cpus <= GIC_NCPU) {
1923             gic_version = VIRT_GIC_VERSION_2;
1924         } else if (gics_supported & VIRT_GIC_VERSION_3_MASK) {
1925             /*
1926              * in case the host does not support v2 emulation or
1927              * the end-user requested more than 8 VCPUs we now default
1928              * to v3. In any case defaulting to v2 would be broken.
1929              */
1930             gic_version = VIRT_GIC_VERSION_3;
1931         } else if (max_cpus > GIC_NCPU) {
1932             error_report("%s only supports GICv2 emulation but more than 8 "
1933                          "vcpus are requested", accel_name);
1934             exit(1);
1935         }
1936         break;
1937     case VIRT_GIC_VERSION_2:
1938     case VIRT_GIC_VERSION_3:
1939     case VIRT_GIC_VERSION_4:
1940         break;
1941     }
1942 
1943     /* Check chosen version is effectively supported */
1944     switch (gic_version) {
1945     case VIRT_GIC_VERSION_2:
1946         if (!(gics_supported & VIRT_GIC_VERSION_2_MASK)) {
1947             error_report("%s does not support GICv2 emulation", accel_name);
1948             exit(1);
1949         }
1950         break;
1951     case VIRT_GIC_VERSION_3:
1952         if (!(gics_supported & VIRT_GIC_VERSION_3_MASK)) {
1953             error_report("%s does not support GICv3 emulation", accel_name);
1954             exit(1);
1955         }
1956         break;
1957     case VIRT_GIC_VERSION_4:
1958         if (!(gics_supported & VIRT_GIC_VERSION_4_MASK)) {
1959             error_report("%s does not support GICv4 emulation, is virtualization=on?",
1960                          accel_name);
1961             exit(1);
1962         }
1963         break;
1964     default:
1965         error_report("logic error in finalize_gic_version");
1966         exit(1);
1967         break;
1968     }
1969 
1970     return gic_version;
1971 }
1972 
1973 /*
1974  * finalize_gic_version - Determines the final gic_version
1975  * according to the gic-version property
1976  *
1977  * Default GIC type is v2
1978  */
1979 static void finalize_gic_version(VirtMachineState *vms)
1980 {
1981     const char *accel_name = current_accel_name();
1982     unsigned int max_cpus = MACHINE(vms)->smp.max_cpus;
1983     int gics_supported = 0;
1984 
1985     /* Determine which GIC versions the current environment supports */
1986     if (kvm_enabled() && kvm_irqchip_in_kernel()) {
1987         int probe_bitmap = kvm_arm_vgic_probe();
1988 
1989         if (!probe_bitmap) {
1990             error_report("Unable to determine GIC version supported by host");
1991             exit(1);
1992         }
1993 
1994         if (probe_bitmap & KVM_ARM_VGIC_V2) {
1995             gics_supported |= VIRT_GIC_VERSION_2_MASK;
1996         }
1997         if (probe_bitmap & KVM_ARM_VGIC_V3) {
1998             gics_supported |= VIRT_GIC_VERSION_3_MASK;
1999         }
2000     } else if (kvm_enabled() && !kvm_irqchip_in_kernel()) {
2001         /* KVM w/o kernel irqchip can only deal with GICv2 */
2002         gics_supported |= VIRT_GIC_VERSION_2_MASK;
2003         accel_name = "KVM with kernel-irqchip=off";
2004     } else if (tcg_enabled() || hvf_enabled() || qtest_enabled())  {
2005         gics_supported |= VIRT_GIC_VERSION_2_MASK;
2006         if (module_object_class_by_name("arm-gicv3")) {
2007             gics_supported |= VIRT_GIC_VERSION_3_MASK;
2008             if (vms->virt) {
2009                 /* GICv4 only makes sense if CPU has EL2 */
2010                 gics_supported |= VIRT_GIC_VERSION_4_MASK;
2011             }
2012         }
2013     } else {
2014         error_report("Unsupported accelerator, can not determine GIC support");
2015         exit(1);
2016     }
2017 
2018     /*
2019      * Then convert helpers like host/max to concrete GIC versions and ensure
2020      * the desired version is supported
2021      */
2022     vms->gic_version = finalize_gic_version_do(accel_name, vms->gic_version,
2023                                                gics_supported, max_cpus);
2024 }
2025 
2026 /*
2027  * virt_cpu_post_init() must be called after the CPUs have
2028  * been realized and the GIC has been created.
2029  */
2030 static void virt_cpu_post_init(VirtMachineState *vms, MemoryRegion *sysmem)
2031 {
2032     int max_cpus = MACHINE(vms)->smp.max_cpus;
2033     bool aarch64, pmu, steal_time;
2034     CPUState *cpu;
2035 
2036     aarch64 = object_property_get_bool(OBJECT(first_cpu), "aarch64", NULL);
2037     pmu = object_property_get_bool(OBJECT(first_cpu), "pmu", NULL);
2038     steal_time = object_property_get_bool(OBJECT(first_cpu),
2039                                           "kvm-steal-time", NULL);
2040 
2041     if (kvm_enabled()) {
2042         hwaddr pvtime_reg_base = vms->memmap[VIRT_PVTIME].base;
2043         hwaddr pvtime_reg_size = vms->memmap[VIRT_PVTIME].size;
2044 
2045         if (steal_time) {
2046             MemoryRegion *pvtime = g_new(MemoryRegion, 1);
2047             hwaddr pvtime_size = max_cpus * PVTIME_SIZE_PER_CPU;
2048 
2049             /* The memory region size must be a multiple of host page size. */
2050             pvtime_size = REAL_HOST_PAGE_ALIGN(pvtime_size);
2051 
2052             if (pvtime_size > pvtime_reg_size) {
2053                 error_report("pvtime requires a %" HWADDR_PRId
2054                              " byte memory region for %d CPUs,"
2055                              " but only %" HWADDR_PRId " has been reserved",
2056                              pvtime_size, max_cpus, pvtime_reg_size);
2057                 exit(1);
2058             }
2059 
2060             memory_region_init_ram(pvtime, NULL, "pvtime", pvtime_size, NULL);
2061             memory_region_add_subregion(sysmem, pvtime_reg_base, pvtime);
2062         }
2063 
2064         CPU_FOREACH(cpu) {
2065             if (pmu) {
2066                 assert(arm_feature(&ARM_CPU(cpu)->env, ARM_FEATURE_PMU));
2067                 if (kvm_irqchip_in_kernel()) {
2068                     kvm_arm_pmu_set_irq(ARM_CPU(cpu), VIRTUAL_PMU_IRQ);
2069                 }
2070                 kvm_arm_pmu_init(ARM_CPU(cpu));
2071             }
2072             if (steal_time) {
2073                 kvm_arm_pvtime_init(ARM_CPU(cpu), pvtime_reg_base
2074                                                   + cpu->cpu_index
2075                                                     * PVTIME_SIZE_PER_CPU);
2076             }
2077         }
2078     } else {
2079         if (aarch64 && vms->highmem) {
2080             int requested_pa_size = 64 - clz64(vms->highest_gpa);
2081             int pamax = arm_pamax(ARM_CPU(first_cpu));
2082 
2083             if (pamax < requested_pa_size) {
2084                 error_report("VCPU supports less PA bits (%d) than "
2085                              "requested by the memory map (%d)",
2086                              pamax, requested_pa_size);
2087                 exit(1);
2088             }
2089         }
2090     }
2091 }
2092 
2093 static void machvirt_init(MachineState *machine)
2094 {
2095     VirtMachineState *vms = VIRT_MACHINE(machine);
2096     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(machine);
2097     MachineClass *mc = MACHINE_GET_CLASS(machine);
2098     const CPUArchIdList *possible_cpus;
2099     MemoryRegion *sysmem = get_system_memory();
2100     MemoryRegion *secure_sysmem = NULL;
2101     MemoryRegion *tag_sysmem = NULL;
2102     MemoryRegion *secure_tag_sysmem = NULL;
2103     int n, virt_max_cpus;
2104     bool firmware_loaded;
2105     bool aarch64 = true;
2106     bool has_ged = !vmc->no_ged;
2107     unsigned int smp_cpus = machine->smp.cpus;
2108     unsigned int max_cpus = machine->smp.max_cpus;
2109 
2110     possible_cpus = mc->possible_cpu_arch_ids(machine);
2111 
2112     /*
2113      * In accelerated mode, the memory map is computed earlier in kvm_type()
2114      * to create a VM with the right number of IPA bits.
2115      */
2116     if (!vms->memmap) {
2117         Object *cpuobj;
2118         ARMCPU *armcpu;
2119         int pa_bits;
2120 
2121         /*
2122          * Instantiate a temporary CPU object to find out about what
2123          * we are about to deal with. Once this is done, get rid of
2124          * the object.
2125          */
2126         cpuobj = object_new(possible_cpus->cpus[0].type);
2127         armcpu = ARM_CPU(cpuobj);
2128 
2129         pa_bits = arm_pamax(armcpu);
2130 
2131         object_unref(cpuobj);
2132 
2133         virt_set_memmap(vms, pa_bits);
2134     }
2135 
2136     /* We can probe only here because during property set
2137      * KVM is not available yet
2138      */
2139     finalize_gic_version(vms);
2140 
2141     if (vms->secure) {
2142         /*
2143          * The Secure view of the world is the same as the NonSecure,
2144          * but with a few extra devices. Create it as a container region
2145          * containing the system memory at low priority; any secure-only
2146          * devices go in at higher priority and take precedence.
2147          */
2148         secure_sysmem = g_new(MemoryRegion, 1);
2149         memory_region_init(secure_sysmem, OBJECT(machine), "secure-memory",
2150                            UINT64_MAX);
2151         memory_region_add_subregion_overlap(secure_sysmem, 0, sysmem, -1);
2152     }
2153 
2154     firmware_loaded = virt_firmware_init(vms, sysmem,
2155                                          secure_sysmem ?: sysmem);
2156 
2157     /* If we have an EL3 boot ROM then the assumption is that it will
2158      * implement PSCI itself, so disable QEMU's internal implementation
2159      * so it doesn't get in the way. Instead of starting secondary
2160      * CPUs in PSCI powerdown state we will start them all running and
2161      * let the boot ROM sort them out.
2162      * The usual case is that we do use QEMU's PSCI implementation;
2163      * if the guest has EL2 then we will use SMC as the conduit,
2164      * and otherwise we will use HVC (for backwards compatibility and
2165      * because if we're using KVM then we must use HVC).
2166      */
2167     if (vms->secure && firmware_loaded) {
2168         vms->psci_conduit = QEMU_PSCI_CONDUIT_DISABLED;
2169     } else if (vms->virt) {
2170         vms->psci_conduit = QEMU_PSCI_CONDUIT_SMC;
2171     } else {
2172         vms->psci_conduit = QEMU_PSCI_CONDUIT_HVC;
2173     }
2174 
2175     /*
2176      * The maximum number of CPUs depends on the GIC version, or on how
2177      * many redistributors we can fit into the memory map (which in turn
2178      * depends on whether this is a GICv3 or v4).
2179      */
2180     if (vms->gic_version == VIRT_GIC_VERSION_2) {
2181         virt_max_cpus = GIC_NCPU;
2182     } else {
2183         virt_max_cpus = virt_redist_capacity(vms, VIRT_GIC_REDIST);
2184         if (vms->highmem_redists) {
2185             virt_max_cpus += virt_redist_capacity(vms, VIRT_HIGH_GIC_REDIST2);
2186         }
2187     }
2188 
2189     if (max_cpus > virt_max_cpus) {
2190         error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "
2191                      "supported by machine 'mach-virt' (%d)",
2192                      max_cpus, virt_max_cpus);
2193         if (vms->gic_version != VIRT_GIC_VERSION_2 && !vms->highmem_redists) {
2194             error_printf("Try 'highmem-redists=on' for more CPUs\n");
2195         }
2196 
2197         exit(1);
2198     }
2199 
2200     if (vms->secure && (kvm_enabled() || hvf_enabled())) {
2201         error_report("mach-virt: %s does not support providing "
2202                      "Security extensions (TrustZone) to the guest CPU",
2203                      current_accel_name());
2204         exit(1);
2205     }
2206 
2207     if (vms->virt && (kvm_enabled() || hvf_enabled())) {
2208         error_report("mach-virt: %s does not support providing "
2209                      "Virtualization extensions to the guest CPU",
2210                      current_accel_name());
2211         exit(1);
2212     }
2213 
2214     if (vms->mte && (kvm_enabled() || hvf_enabled())) {
2215         error_report("mach-virt: %s does not support providing "
2216                      "MTE to the guest CPU",
2217                      current_accel_name());
2218         exit(1);
2219     }
2220 
2221     create_fdt(vms);
2222 
2223     assert(possible_cpus->len == max_cpus);
2224     for (n = 0; n < possible_cpus->len; n++) {
2225         Object *cpuobj;
2226         CPUState *cs;
2227 
2228         if (n >= smp_cpus) {
2229             break;
2230         }
2231 
2232         cpuobj = object_new(possible_cpus->cpus[n].type);
2233         object_property_set_int(cpuobj, "mp-affinity",
2234                                 possible_cpus->cpus[n].arch_id, NULL);
2235 
2236         cs = CPU(cpuobj);
2237         cs->cpu_index = n;
2238 
2239         numa_cpu_pre_plug(&possible_cpus->cpus[cs->cpu_index], DEVICE(cpuobj),
2240                           &error_fatal);
2241 
2242         aarch64 &= object_property_get_bool(cpuobj, "aarch64", NULL);
2243 
2244         if (!vms->secure) {
2245             object_property_set_bool(cpuobj, "has_el3", false, NULL);
2246         }
2247 
2248         if (!vms->virt && object_property_find(cpuobj, "has_el2")) {
2249             object_property_set_bool(cpuobj, "has_el2", false, NULL);
2250         }
2251 
2252         if (vmc->kvm_no_adjvtime &&
2253             object_property_find(cpuobj, "kvm-no-adjvtime")) {
2254             object_property_set_bool(cpuobj, "kvm-no-adjvtime", true, NULL);
2255         }
2256 
2257         if (vmc->no_kvm_steal_time &&
2258             object_property_find(cpuobj, "kvm-steal-time")) {
2259             object_property_set_bool(cpuobj, "kvm-steal-time", false, NULL);
2260         }
2261 
2262         if (vmc->no_pmu && object_property_find(cpuobj, "pmu")) {
2263             object_property_set_bool(cpuobj, "pmu", false, NULL);
2264         }
2265 
2266         if (vmc->no_tcg_lpa2 && object_property_find(cpuobj, "lpa2")) {
2267             object_property_set_bool(cpuobj, "lpa2", false, NULL);
2268         }
2269 
2270         if (object_property_find(cpuobj, "reset-cbar")) {
2271             object_property_set_int(cpuobj, "reset-cbar",
2272                                     vms->memmap[VIRT_CPUPERIPHS].base,
2273                                     &error_abort);
2274         }
2275 
2276         object_property_set_link(cpuobj, "memory", OBJECT(sysmem),
2277                                  &error_abort);
2278         if (vms->secure) {
2279             object_property_set_link(cpuobj, "secure-memory",
2280                                      OBJECT(secure_sysmem), &error_abort);
2281         }
2282 
2283         if (vms->mte) {
2284             /* Create the memory region only once, but link to all cpus. */
2285             if (!tag_sysmem) {
2286                 /*
2287                  * The property exists only if MemTag is supported.
2288                  * If it is, we must allocate the ram to back that up.
2289                  */
2290                 if (!object_property_find(cpuobj, "tag-memory")) {
2291                     error_report("MTE requested, but not supported "
2292                                  "by the guest CPU");
2293                     exit(1);
2294                 }
2295 
2296                 tag_sysmem = g_new(MemoryRegion, 1);
2297                 memory_region_init(tag_sysmem, OBJECT(machine),
2298                                    "tag-memory", UINT64_MAX / 32);
2299 
2300                 if (vms->secure) {
2301                     secure_tag_sysmem = g_new(MemoryRegion, 1);
2302                     memory_region_init(secure_tag_sysmem, OBJECT(machine),
2303                                        "secure-tag-memory", UINT64_MAX / 32);
2304 
2305                     /* As with ram, secure-tag takes precedence over tag.  */
2306                     memory_region_add_subregion_overlap(secure_tag_sysmem, 0,
2307                                                         tag_sysmem, -1);
2308                 }
2309             }
2310 
2311             object_property_set_link(cpuobj, "tag-memory", OBJECT(tag_sysmem),
2312                                      &error_abort);
2313             if (vms->secure) {
2314                 object_property_set_link(cpuobj, "secure-tag-memory",
2315                                          OBJECT(secure_tag_sysmem),
2316                                          &error_abort);
2317             }
2318         }
2319 
2320         qdev_realize(DEVICE(cpuobj), NULL, &error_fatal);
2321         object_unref(cpuobj);
2322     }
2323 
2324     /* Now we've created the CPUs we can see if they have the hypvirt timer */
2325     vms->ns_el2_virt_timer_irq = ns_el2_virt_timer_present() &&
2326         !vmc->no_ns_el2_virt_timer_irq;
2327 
2328     fdt_add_timer_nodes(vms);
2329     fdt_add_cpu_nodes(vms);
2330 
2331     memory_region_add_subregion(sysmem, vms->memmap[VIRT_MEM].base,
2332                                 machine->ram);
2333 
2334     virt_flash_fdt(vms, sysmem, secure_sysmem ?: sysmem);
2335 
2336     create_gic(vms, sysmem);
2337 
2338     virt_cpu_post_init(vms, sysmem);
2339 
2340     fdt_add_pmu_nodes(vms);
2341 
2342     /*
2343      * The first UART always exists. If the security extensions are
2344      * enabled, the second UART also always exists. Otherwise, it only exists
2345      * if a backend is configured explicitly via '-serial <backend>'.
2346      * This avoids potentially breaking existing user setups that expect
2347      * only one NonSecure UART to be present (for instance, older EDK2
2348      * binaries).
2349      *
2350      * The nodes end up in the DTB in reverse order of creation, so we must
2351      * create UART0 last to ensure it appears as the first node in the DTB,
2352      * for compatibility with guest software that just iterates through the
2353      * DTB to find the first UART, as older versions of EDK2 do.
2354      * DTB readers that follow the spec, as Linux does, should honour the
2355      * aliases node information and /chosen/stdout-path regardless of
2356      * the order that nodes appear in the DTB.
2357      *
2358      * For similar back-compatibility reasons, if UART1 is the secure UART
2359      * we create it second (and so it appears first in the DTB), because
2360      * that's what QEMU has always done.
2361      */
2362     if (!vms->secure) {
2363         Chardev *serial1 = serial_hd(1);
2364 
2365         if (serial1) {
2366             vms->second_ns_uart_present = true;
2367             create_uart(vms, VIRT_UART1, sysmem, serial1, false);
2368         }
2369     }
2370     create_uart(vms, VIRT_UART0, sysmem, serial_hd(0), false);
2371     if (vms->secure) {
2372         create_uart(vms, VIRT_UART1, secure_sysmem, serial_hd(1), true);
2373     }
2374 
2375     if (vms->secure) {
2376         create_secure_ram(vms, secure_sysmem, secure_tag_sysmem);
2377     }
2378 
2379     if (tag_sysmem) {
2380         create_tag_ram(tag_sysmem, vms->memmap[VIRT_MEM].base,
2381                        machine->ram_size, "mach-virt.tag");
2382     }
2383 
2384     vms->highmem_ecam &= (!firmware_loaded || aarch64);
2385 
2386     create_rtc(vms);
2387 
2388     create_pcie(vms);
2389 
2390     if (has_ged && aarch64 && firmware_loaded && virt_is_acpi_enabled(vms)) {
2391         vms->acpi_dev = create_acpi_ged(vms);
2392     } else {
2393         create_gpio_devices(vms, VIRT_GPIO, sysmem);
2394     }
2395 
2396     if (vms->secure && !vmc->no_secure_gpio) {
2397         create_gpio_devices(vms, VIRT_SECURE_GPIO, secure_sysmem);
2398     }
2399 
2400      /* connect powerdown request */
2401      vms->powerdown_notifier.notify = virt_powerdown_req;
2402      qemu_register_powerdown_notifier(&vms->powerdown_notifier);
2403 
2404     /* Create mmio transports, so the user can create virtio backends
2405      * (which will be automatically plugged in to the transports). If
2406      * no backend is created the transport will just sit harmlessly idle.
2407      */
2408     create_virtio_devices(vms);
2409 
2410     vms->fw_cfg = create_fw_cfg(vms, &address_space_memory);
2411     rom_set_fw(vms->fw_cfg);
2412 
2413     create_platform_bus(vms);
2414 
2415     if (machine->nvdimms_state->is_enabled) {
2416         const struct AcpiGenericAddress arm_virt_nvdimm_acpi_dsmio = {
2417             .space_id = AML_AS_SYSTEM_MEMORY,
2418             .address = vms->memmap[VIRT_NVDIMM_ACPI].base,
2419             .bit_width = NVDIMM_ACPI_IO_LEN << 3
2420         };
2421 
2422         nvdimm_init_acpi_state(machine->nvdimms_state, sysmem,
2423                                arm_virt_nvdimm_acpi_dsmio,
2424                                vms->fw_cfg, OBJECT(vms));
2425     }
2426 
2427     vms->bootinfo.ram_size = machine->ram_size;
2428     vms->bootinfo.board_id = -1;
2429     vms->bootinfo.loader_start = vms->memmap[VIRT_MEM].base;
2430     vms->bootinfo.get_dtb = machvirt_dtb;
2431     vms->bootinfo.skip_dtb_autoload = true;
2432     vms->bootinfo.firmware_loaded = firmware_loaded;
2433     vms->bootinfo.psci_conduit = vms->psci_conduit;
2434     arm_load_kernel(ARM_CPU(first_cpu), machine, &vms->bootinfo);
2435 
2436     vms->machine_done.notify = virt_machine_done;
2437     qemu_add_machine_init_done_notifier(&vms->machine_done);
2438 }
2439 
2440 static bool virt_get_secure(Object *obj, Error **errp)
2441 {
2442     VirtMachineState *vms = VIRT_MACHINE(obj);
2443 
2444     return vms->secure;
2445 }
2446 
2447 static void virt_set_secure(Object *obj, bool value, Error **errp)
2448 {
2449     VirtMachineState *vms = VIRT_MACHINE(obj);
2450 
2451     vms->secure = value;
2452 }
2453 
2454 static bool virt_get_virt(Object *obj, Error **errp)
2455 {
2456     VirtMachineState *vms = VIRT_MACHINE(obj);
2457 
2458     return vms->virt;
2459 }
2460 
2461 static void virt_set_virt(Object *obj, bool value, Error **errp)
2462 {
2463     VirtMachineState *vms = VIRT_MACHINE(obj);
2464 
2465     vms->virt = value;
2466 }
2467 
2468 static bool virt_get_highmem(Object *obj, Error **errp)
2469 {
2470     VirtMachineState *vms = VIRT_MACHINE(obj);
2471 
2472     return vms->highmem;
2473 }
2474 
2475 static void virt_set_highmem(Object *obj, bool value, Error **errp)
2476 {
2477     VirtMachineState *vms = VIRT_MACHINE(obj);
2478 
2479     vms->highmem = value;
2480 }
2481 
2482 static bool virt_get_compact_highmem(Object *obj, Error **errp)
2483 {
2484     VirtMachineState *vms = VIRT_MACHINE(obj);
2485 
2486     return vms->highmem_compact;
2487 }
2488 
2489 static void virt_set_compact_highmem(Object *obj, bool value, Error **errp)
2490 {
2491     VirtMachineState *vms = VIRT_MACHINE(obj);
2492 
2493     vms->highmem_compact = value;
2494 }
2495 
2496 static bool virt_get_highmem_redists(Object *obj, Error **errp)
2497 {
2498     VirtMachineState *vms = VIRT_MACHINE(obj);
2499 
2500     return vms->highmem_redists;
2501 }
2502 
2503 static void virt_set_highmem_redists(Object *obj, bool value, Error **errp)
2504 {
2505     VirtMachineState *vms = VIRT_MACHINE(obj);
2506 
2507     vms->highmem_redists = value;
2508 }
2509 
2510 static bool virt_get_highmem_ecam(Object *obj, Error **errp)
2511 {
2512     VirtMachineState *vms = VIRT_MACHINE(obj);
2513 
2514     return vms->highmem_ecam;
2515 }
2516 
2517 static void virt_set_highmem_ecam(Object *obj, bool value, Error **errp)
2518 {
2519     VirtMachineState *vms = VIRT_MACHINE(obj);
2520 
2521     vms->highmem_ecam = value;
2522 }
2523 
2524 static bool virt_get_highmem_mmio(Object *obj, Error **errp)
2525 {
2526     VirtMachineState *vms = VIRT_MACHINE(obj);
2527 
2528     return vms->highmem_mmio;
2529 }
2530 
2531 static void virt_set_highmem_mmio(Object *obj, bool value, Error **errp)
2532 {
2533     VirtMachineState *vms = VIRT_MACHINE(obj);
2534 
2535     vms->highmem_mmio = value;
2536 }
2537 
2538 
2539 static bool virt_get_its(Object *obj, Error **errp)
2540 {
2541     VirtMachineState *vms = VIRT_MACHINE(obj);
2542 
2543     return vms->its;
2544 }
2545 
2546 static void virt_set_its(Object *obj, bool value, Error **errp)
2547 {
2548     VirtMachineState *vms = VIRT_MACHINE(obj);
2549 
2550     vms->its = value;
2551 }
2552 
2553 static bool virt_get_dtb_randomness(Object *obj, Error **errp)
2554 {
2555     VirtMachineState *vms = VIRT_MACHINE(obj);
2556 
2557     return vms->dtb_randomness;
2558 }
2559 
2560 static void virt_set_dtb_randomness(Object *obj, bool value, Error **errp)
2561 {
2562     VirtMachineState *vms = VIRT_MACHINE(obj);
2563 
2564     vms->dtb_randomness = value;
2565 }
2566 
2567 static char *virt_get_oem_id(Object *obj, Error **errp)
2568 {
2569     VirtMachineState *vms = VIRT_MACHINE(obj);
2570 
2571     return g_strdup(vms->oem_id);
2572 }
2573 
2574 static void virt_set_oem_id(Object *obj, const char *value, Error **errp)
2575 {
2576     VirtMachineState *vms = VIRT_MACHINE(obj);
2577     size_t len = strlen(value);
2578 
2579     if (len > 6) {
2580         error_setg(errp,
2581                    "User specified oem-id value is bigger than 6 bytes in size");
2582         return;
2583     }
2584 
2585     strncpy(vms->oem_id, value, 6);
2586 }
2587 
2588 static char *virt_get_oem_table_id(Object *obj, Error **errp)
2589 {
2590     VirtMachineState *vms = VIRT_MACHINE(obj);
2591 
2592     return g_strdup(vms->oem_table_id);
2593 }
2594 
2595 static void virt_set_oem_table_id(Object *obj, const char *value,
2596                                   Error **errp)
2597 {
2598     VirtMachineState *vms = VIRT_MACHINE(obj);
2599     size_t len = strlen(value);
2600 
2601     if (len > 8) {
2602         error_setg(errp,
2603                    "User specified oem-table-id value is bigger than 8 bytes in size");
2604         return;
2605     }
2606     strncpy(vms->oem_table_id, value, 8);
2607 }
2608 
2609 
2610 bool virt_is_acpi_enabled(VirtMachineState *vms)
2611 {
2612     if (vms->acpi == ON_OFF_AUTO_OFF) {
2613         return false;
2614     }
2615     return true;
2616 }
2617 
2618 static void virt_get_acpi(Object *obj, Visitor *v, const char *name,
2619                           void *opaque, Error **errp)
2620 {
2621     VirtMachineState *vms = VIRT_MACHINE(obj);
2622     OnOffAuto acpi = vms->acpi;
2623 
2624     visit_type_OnOffAuto(v, name, &acpi, errp);
2625 }
2626 
2627 static void virt_set_acpi(Object *obj, Visitor *v, const char *name,
2628                           void *opaque, Error **errp)
2629 {
2630     VirtMachineState *vms = VIRT_MACHINE(obj);
2631 
2632     visit_type_OnOffAuto(v, name, &vms->acpi, errp);
2633 }
2634 
2635 static bool virt_get_ras(Object *obj, Error **errp)
2636 {
2637     VirtMachineState *vms = VIRT_MACHINE(obj);
2638 
2639     return vms->ras;
2640 }
2641 
2642 static void virt_set_ras(Object *obj, bool value, Error **errp)
2643 {
2644     VirtMachineState *vms = VIRT_MACHINE(obj);
2645 
2646     vms->ras = value;
2647 }
2648 
2649 static bool virt_get_mte(Object *obj, Error **errp)
2650 {
2651     VirtMachineState *vms = VIRT_MACHINE(obj);
2652 
2653     return vms->mte;
2654 }
2655 
2656 static void virt_set_mte(Object *obj, bool value, Error **errp)
2657 {
2658     VirtMachineState *vms = VIRT_MACHINE(obj);
2659 
2660     vms->mte = value;
2661 }
2662 
2663 static char *virt_get_gic_version(Object *obj, Error **errp)
2664 {
2665     VirtMachineState *vms = VIRT_MACHINE(obj);
2666     const char *val;
2667 
2668     switch (vms->gic_version) {
2669     case VIRT_GIC_VERSION_4:
2670         val = "4";
2671         break;
2672     case VIRT_GIC_VERSION_3:
2673         val = "3";
2674         break;
2675     default:
2676         val = "2";
2677         break;
2678     }
2679     return g_strdup(val);
2680 }
2681 
2682 static void virt_set_gic_version(Object *obj, const char *value, Error **errp)
2683 {
2684     VirtMachineState *vms = VIRT_MACHINE(obj);
2685 
2686     if (!strcmp(value, "4")) {
2687         vms->gic_version = VIRT_GIC_VERSION_4;
2688     } else if (!strcmp(value, "3")) {
2689         vms->gic_version = VIRT_GIC_VERSION_3;
2690     } else if (!strcmp(value, "2")) {
2691         vms->gic_version = VIRT_GIC_VERSION_2;
2692     } else if (!strcmp(value, "host")) {
2693         vms->gic_version = VIRT_GIC_VERSION_HOST; /* Will probe later */
2694     } else if (!strcmp(value, "max")) {
2695         vms->gic_version = VIRT_GIC_VERSION_MAX; /* Will probe later */
2696     } else {
2697         error_setg(errp, "Invalid gic-version value");
2698         error_append_hint(errp, "Valid values are 3, 2, host, max.\n");
2699     }
2700 }
2701 
2702 static char *virt_get_iommu(Object *obj, Error **errp)
2703 {
2704     VirtMachineState *vms = VIRT_MACHINE(obj);
2705 
2706     switch (vms->iommu) {
2707     case VIRT_IOMMU_NONE:
2708         return g_strdup("none");
2709     case VIRT_IOMMU_SMMUV3:
2710         return g_strdup("smmuv3");
2711     default:
2712         g_assert_not_reached();
2713     }
2714 }
2715 
2716 static void virt_set_iommu(Object *obj, const char *value, Error **errp)
2717 {
2718     VirtMachineState *vms = VIRT_MACHINE(obj);
2719 
2720     if (!strcmp(value, "smmuv3")) {
2721         vms->iommu = VIRT_IOMMU_SMMUV3;
2722     } else if (!strcmp(value, "none")) {
2723         vms->iommu = VIRT_IOMMU_NONE;
2724     } else {
2725         error_setg(errp, "Invalid iommu value");
2726         error_append_hint(errp, "Valid values are none, smmuv3.\n");
2727     }
2728 }
2729 
2730 static bool virt_get_default_bus_bypass_iommu(Object *obj, Error **errp)
2731 {
2732     VirtMachineState *vms = VIRT_MACHINE(obj);
2733 
2734     return vms->default_bus_bypass_iommu;
2735 }
2736 
2737 static void virt_set_default_bus_bypass_iommu(Object *obj, bool value,
2738                                               Error **errp)
2739 {
2740     VirtMachineState *vms = VIRT_MACHINE(obj);
2741 
2742     vms->default_bus_bypass_iommu = value;
2743 }
2744 
2745 static CpuInstanceProperties
2746 virt_cpu_index_to_props(MachineState *ms, unsigned cpu_index)
2747 {
2748     MachineClass *mc = MACHINE_GET_CLASS(ms);
2749     const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
2750 
2751     assert(cpu_index < possible_cpus->len);
2752     return possible_cpus->cpus[cpu_index].props;
2753 }
2754 
2755 static int64_t virt_get_default_cpu_node_id(const MachineState *ms, int idx)
2756 {
2757     int64_t socket_id = ms->possible_cpus->cpus[idx].props.socket_id;
2758 
2759     return socket_id % ms->numa_state->num_nodes;
2760 }
2761 
2762 static const CPUArchIdList *virt_possible_cpu_arch_ids(MachineState *ms)
2763 {
2764     int n;
2765     unsigned int max_cpus = ms->smp.max_cpus;
2766     VirtMachineState *vms = VIRT_MACHINE(ms);
2767     MachineClass *mc = MACHINE_GET_CLASS(vms);
2768 
2769     if (ms->possible_cpus) {
2770         assert(ms->possible_cpus->len == max_cpus);
2771         return ms->possible_cpus;
2772     }
2773 
2774     ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
2775                                   sizeof(CPUArchId) * max_cpus);
2776     ms->possible_cpus->len = max_cpus;
2777     for (n = 0; n < ms->possible_cpus->len; n++) {
2778         ms->possible_cpus->cpus[n].type = ms->cpu_type;
2779         ms->possible_cpus->cpus[n].arch_id =
2780             virt_cpu_mp_affinity(vms, n);
2781 
2782         assert(!mc->smp_props.dies_supported);
2783         ms->possible_cpus->cpus[n].props.has_socket_id = true;
2784         ms->possible_cpus->cpus[n].props.socket_id =
2785             n / (ms->smp.clusters * ms->smp.cores * ms->smp.threads);
2786         ms->possible_cpus->cpus[n].props.has_cluster_id = true;
2787         ms->possible_cpus->cpus[n].props.cluster_id =
2788             (n / (ms->smp.cores * ms->smp.threads)) % ms->smp.clusters;
2789         ms->possible_cpus->cpus[n].props.has_core_id = true;
2790         ms->possible_cpus->cpus[n].props.core_id =
2791             (n / ms->smp.threads) % ms->smp.cores;
2792         ms->possible_cpus->cpus[n].props.has_thread_id = true;
2793         ms->possible_cpus->cpus[n].props.thread_id =
2794             n % ms->smp.threads;
2795     }
2796     return ms->possible_cpus;
2797 }
2798 
2799 static void virt_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
2800                                  Error **errp)
2801 {
2802     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2803     const MachineState *ms = MACHINE(hotplug_dev);
2804     const bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
2805 
2806     if (!vms->acpi_dev) {
2807         error_setg(errp,
2808                    "memory hotplug is not enabled: missing acpi-ged device");
2809         return;
2810     }
2811 
2812     if (vms->mte) {
2813         error_setg(errp, "memory hotplug is not enabled: MTE is enabled");
2814         return;
2815     }
2816 
2817     if (is_nvdimm && !ms->nvdimms_state->is_enabled) {
2818         error_setg(errp, "nvdimm is not enabled: add 'nvdimm=on' to '-M'");
2819         return;
2820     }
2821 
2822     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev), errp);
2823 }
2824 
2825 static void virt_memory_plug(HotplugHandler *hotplug_dev,
2826                              DeviceState *dev, Error **errp)
2827 {
2828     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2829     MachineState *ms = MACHINE(hotplug_dev);
2830     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
2831 
2832     pc_dimm_plug(PC_DIMM(dev), MACHINE(vms));
2833 
2834     if (is_nvdimm) {
2835         nvdimm_plug(ms->nvdimms_state);
2836     }
2837 
2838     hotplug_handler_plug(HOTPLUG_HANDLER(vms->acpi_dev),
2839                          dev, &error_abort);
2840 }
2841 
2842 static void virt_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
2843                                             DeviceState *dev, Error **errp)
2844 {
2845     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2846 
2847     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2848         virt_memory_pre_plug(hotplug_dev, dev, errp);
2849     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MD_PCI)) {
2850         virtio_md_pci_pre_plug(VIRTIO_MD_PCI(dev), MACHINE(hotplug_dev), errp);
2851     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
2852         hwaddr db_start = 0, db_end = 0;
2853         QList *reserved_regions;
2854         char *resv_prop_str;
2855 
2856         if (vms->iommu != VIRT_IOMMU_NONE) {
2857             error_setg(errp, "virt machine does not support multiple IOMMUs");
2858             return;
2859         }
2860 
2861         switch (vms->msi_controller) {
2862         case VIRT_MSI_CTRL_NONE:
2863             return;
2864         case VIRT_MSI_CTRL_ITS:
2865             /* GITS_TRANSLATER page */
2866             db_start = base_memmap[VIRT_GIC_ITS].base + 0x10000;
2867             db_end = base_memmap[VIRT_GIC_ITS].base +
2868                      base_memmap[VIRT_GIC_ITS].size - 1;
2869             break;
2870         case VIRT_MSI_CTRL_GICV2M:
2871             /* MSI_SETSPI_NS page */
2872             db_start = base_memmap[VIRT_GIC_V2M].base;
2873             db_end = db_start + base_memmap[VIRT_GIC_V2M].size - 1;
2874             break;
2875         }
2876         resv_prop_str = g_strdup_printf("0x%"PRIx64":0x%"PRIx64":%u",
2877                                         db_start, db_end,
2878                                         VIRTIO_IOMMU_RESV_MEM_T_MSI);
2879 
2880         reserved_regions = qlist_new();
2881         qlist_append_str(reserved_regions, resv_prop_str);
2882         qdev_prop_set_array(dev, "reserved-regions", reserved_regions);
2883         g_free(resv_prop_str);
2884     }
2885 }
2886 
2887 static void virt_machine_device_plug_cb(HotplugHandler *hotplug_dev,
2888                                         DeviceState *dev, Error **errp)
2889 {
2890     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2891 
2892     if (vms->platform_bus_dev) {
2893         MachineClass *mc = MACHINE_GET_CLASS(vms);
2894 
2895         if (device_is_dynamic_sysbus(mc, dev)) {
2896             platform_bus_link_device(PLATFORM_BUS_DEVICE(vms->platform_bus_dev),
2897                                      SYS_BUS_DEVICE(dev));
2898         }
2899     }
2900 
2901     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2902         virt_memory_plug(hotplug_dev, dev, errp);
2903     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MD_PCI)) {
2904         virtio_md_pci_plug(VIRTIO_MD_PCI(dev), MACHINE(hotplug_dev), errp);
2905     }
2906 
2907     if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
2908         PCIDevice *pdev = PCI_DEVICE(dev);
2909 
2910         vms->iommu = VIRT_IOMMU_VIRTIO;
2911         vms->virtio_iommu_bdf = pci_get_bdf(pdev);
2912         create_virtio_iommu_dt_bindings(vms);
2913     }
2914 }
2915 
2916 static void virt_dimm_unplug_request(HotplugHandler *hotplug_dev,
2917                                      DeviceState *dev, Error **errp)
2918 {
2919     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2920 
2921     if (!vms->acpi_dev) {
2922         error_setg(errp,
2923                    "memory hotplug is not enabled: missing acpi-ged device");
2924         return;
2925     }
2926 
2927     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
2928         error_setg(errp, "nvdimm device hot unplug is not supported yet.");
2929         return;
2930     }
2931 
2932     hotplug_handler_unplug_request(HOTPLUG_HANDLER(vms->acpi_dev), dev,
2933                                    errp);
2934 }
2935 
2936 static void virt_dimm_unplug(HotplugHandler *hotplug_dev,
2937                              DeviceState *dev, Error **errp)
2938 {
2939     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2940     Error *local_err = NULL;
2941 
2942     hotplug_handler_unplug(HOTPLUG_HANDLER(vms->acpi_dev), dev, &local_err);
2943     if (local_err) {
2944         goto out;
2945     }
2946 
2947     pc_dimm_unplug(PC_DIMM(dev), MACHINE(vms));
2948     qdev_unrealize(dev);
2949 
2950 out:
2951     error_propagate(errp, local_err);
2952 }
2953 
2954 static void virt_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
2955                                           DeviceState *dev, Error **errp)
2956 {
2957     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2958         virt_dimm_unplug_request(hotplug_dev, dev, errp);
2959     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MD_PCI)) {
2960         virtio_md_pci_unplug_request(VIRTIO_MD_PCI(dev), MACHINE(hotplug_dev),
2961                                      errp);
2962     } else {
2963         error_setg(errp, "device unplug request for unsupported device"
2964                    " type: %s", object_get_typename(OBJECT(dev)));
2965     }
2966 }
2967 
2968 static void virt_machine_device_unplug_cb(HotplugHandler *hotplug_dev,
2969                                           DeviceState *dev, Error **errp)
2970 {
2971     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2972         virt_dimm_unplug(hotplug_dev, dev, errp);
2973     } else if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MD_PCI)) {
2974         virtio_md_pci_unplug(VIRTIO_MD_PCI(dev), MACHINE(hotplug_dev), errp);
2975     } else {
2976         error_setg(errp, "virt: device unplug for unsupported device"
2977                    " type: %s", object_get_typename(OBJECT(dev)));
2978     }
2979 }
2980 
2981 static HotplugHandler *virt_machine_get_hotplug_handler(MachineState *machine,
2982                                                         DeviceState *dev)
2983 {
2984     MachineClass *mc = MACHINE_GET_CLASS(machine);
2985 
2986     if (device_is_dynamic_sysbus(mc, dev) ||
2987         object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
2988         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_MD_PCI) ||
2989         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
2990         return HOTPLUG_HANDLER(machine);
2991     }
2992     return NULL;
2993 }
2994 
2995 /*
2996  * for arm64 kvm_type [7-0] encodes the requested number of bits
2997  * in the IPA address space
2998  */
2999 static int virt_kvm_type(MachineState *ms, const char *type_str)
3000 {
3001     VirtMachineState *vms = VIRT_MACHINE(ms);
3002     int max_vm_pa_size, requested_pa_size;
3003     bool fixed_ipa;
3004 
3005     max_vm_pa_size = kvm_arm_get_max_vm_ipa_size(ms, &fixed_ipa);
3006 
3007     /* we freeze the memory map to compute the highest gpa */
3008     virt_set_memmap(vms, max_vm_pa_size);
3009 
3010     requested_pa_size = 64 - clz64(vms->highest_gpa);
3011 
3012     /*
3013      * KVM requires the IPA size to be at least 32 bits.
3014      */
3015     if (requested_pa_size < 32) {
3016         requested_pa_size = 32;
3017     }
3018 
3019     if (requested_pa_size > max_vm_pa_size) {
3020         error_report("-m and ,maxmem option values "
3021                      "require an IPA range (%d bits) larger than "
3022                      "the one supported by the host (%d bits)",
3023                      requested_pa_size, max_vm_pa_size);
3024         return -1;
3025     }
3026     /*
3027      * We return the requested PA log size, unless KVM only supports
3028      * the implicit legacy 40b IPA setting, in which case the kvm_type
3029      * must be 0.
3030      */
3031     return fixed_ipa ? 0 : requested_pa_size;
3032 }
3033 
3034 static void virt_machine_class_init(ObjectClass *oc, void *data)
3035 {
3036     MachineClass *mc = MACHINE_CLASS(oc);
3037     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
3038     static const char * const valid_cpu_types[] = {
3039 #ifdef CONFIG_TCG
3040         ARM_CPU_TYPE_NAME("cortex-a7"),
3041         ARM_CPU_TYPE_NAME("cortex-a15"),
3042 #ifdef TARGET_AARCH64
3043         ARM_CPU_TYPE_NAME("cortex-a35"),
3044         ARM_CPU_TYPE_NAME("cortex-a55"),
3045         ARM_CPU_TYPE_NAME("cortex-a72"),
3046         ARM_CPU_TYPE_NAME("cortex-a76"),
3047         ARM_CPU_TYPE_NAME("cortex-a710"),
3048         ARM_CPU_TYPE_NAME("a64fx"),
3049         ARM_CPU_TYPE_NAME("neoverse-n1"),
3050         ARM_CPU_TYPE_NAME("neoverse-v1"),
3051         ARM_CPU_TYPE_NAME("neoverse-n2"),
3052 #endif /* TARGET_AARCH64 */
3053 #endif /* CONFIG_TCG */
3054 #ifdef TARGET_AARCH64
3055         ARM_CPU_TYPE_NAME("cortex-a53"),
3056         ARM_CPU_TYPE_NAME("cortex-a57"),
3057 #if defined(CONFIG_KVM) || defined(CONFIG_HVF)
3058         ARM_CPU_TYPE_NAME("host"),
3059 #endif /* CONFIG_KVM || CONFIG_HVF */
3060 #endif /* TARGET_AARCH64 */
3061         ARM_CPU_TYPE_NAME("max"),
3062         NULL
3063     };
3064 
3065     mc->init = machvirt_init;
3066     /* Start with max_cpus set to 512, which is the maximum supported by KVM.
3067      * The value may be reduced later when we have more information about the
3068      * configuration of the particular instance.
3069      */
3070     mc->max_cpus = 512;
3071     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_VFIO_CALXEDA_XGMAC);
3072     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_VFIO_AMD_XGBE);
3073     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_RAMFB_DEVICE);
3074     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_VFIO_PLATFORM);
3075 #ifdef CONFIG_TPM
3076     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
3077 #endif
3078     mc->block_default_type = IF_VIRTIO;
3079     mc->no_cdrom = 1;
3080     mc->pci_allow_0_address = true;
3081     /* We know we will never create a pre-ARMv7 CPU which needs 1K pages */
3082     mc->minimum_page_bits = 12;
3083     mc->possible_cpu_arch_ids = virt_possible_cpu_arch_ids;
3084     mc->cpu_index_to_instance_props = virt_cpu_index_to_props;
3085 #ifdef CONFIG_TCG
3086     mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-a15");
3087 #else
3088     mc->default_cpu_type = ARM_CPU_TYPE_NAME("max");
3089 #endif
3090     mc->valid_cpu_types = valid_cpu_types;
3091     mc->get_default_cpu_node_id = virt_get_default_cpu_node_id;
3092     mc->kvm_type = virt_kvm_type;
3093     assert(!mc->get_hotplug_handler);
3094     mc->get_hotplug_handler = virt_machine_get_hotplug_handler;
3095     hc->pre_plug = virt_machine_device_pre_plug_cb;
3096     hc->plug = virt_machine_device_plug_cb;
3097     hc->unplug_request = virt_machine_device_unplug_request_cb;
3098     hc->unplug = virt_machine_device_unplug_cb;
3099     mc->nvdimm_supported = true;
3100     mc->smp_props.clusters_supported = true;
3101     mc->auto_enable_numa_with_memhp = true;
3102     mc->auto_enable_numa_with_memdev = true;
3103     /* platform instead of architectural choice */
3104     mc->cpu_cluster_has_numa_boundary = true;
3105     mc->default_ram_id = "mach-virt.ram";
3106     mc->default_nic = "virtio-net-pci";
3107 
3108     object_class_property_add(oc, "acpi", "OnOffAuto",
3109         virt_get_acpi, virt_set_acpi,
3110         NULL, NULL);
3111     object_class_property_set_description(oc, "acpi",
3112         "Enable ACPI");
3113     object_class_property_add_bool(oc, "secure", virt_get_secure,
3114                                    virt_set_secure);
3115     object_class_property_set_description(oc, "secure",
3116                                                 "Set on/off to enable/disable the ARM "
3117                                                 "Security Extensions (TrustZone)");
3118 
3119     object_class_property_add_bool(oc, "virtualization", virt_get_virt,
3120                                    virt_set_virt);
3121     object_class_property_set_description(oc, "virtualization",
3122                                           "Set on/off to enable/disable emulating a "
3123                                           "guest CPU which implements the ARM "
3124                                           "Virtualization Extensions");
3125 
3126     object_class_property_add_bool(oc, "highmem", virt_get_highmem,
3127                                    virt_set_highmem);
3128     object_class_property_set_description(oc, "highmem",
3129                                           "Set on/off to enable/disable using "
3130                                           "physical address space above 32 bits");
3131 
3132     object_class_property_add_bool(oc, "compact-highmem",
3133                                    virt_get_compact_highmem,
3134                                    virt_set_compact_highmem);
3135     object_class_property_set_description(oc, "compact-highmem",
3136                                           "Set on/off to enable/disable compact "
3137                                           "layout for high memory regions");
3138 
3139     object_class_property_add_bool(oc, "highmem-redists",
3140                                    virt_get_highmem_redists,
3141                                    virt_set_highmem_redists);
3142     object_class_property_set_description(oc, "highmem-redists",
3143                                           "Set on/off to enable/disable high "
3144                                           "memory region for GICv3 or GICv4 "
3145                                           "redistributor");
3146 
3147     object_class_property_add_bool(oc, "highmem-ecam",
3148                                    virt_get_highmem_ecam,
3149                                    virt_set_highmem_ecam);
3150     object_class_property_set_description(oc, "highmem-ecam",
3151                                           "Set on/off to enable/disable high "
3152                                           "memory region for PCI ECAM");
3153 
3154     object_class_property_add_bool(oc, "highmem-mmio",
3155                                    virt_get_highmem_mmio,
3156                                    virt_set_highmem_mmio);
3157     object_class_property_set_description(oc, "highmem-mmio",
3158                                           "Set on/off to enable/disable high "
3159                                           "memory region for PCI MMIO");
3160 
3161     object_class_property_add_str(oc, "gic-version", virt_get_gic_version,
3162                                   virt_set_gic_version);
3163     object_class_property_set_description(oc, "gic-version",
3164                                           "Set GIC version. "
3165                                           "Valid values are 2, 3, 4, host and max");
3166 
3167     object_class_property_add_str(oc, "iommu", virt_get_iommu, virt_set_iommu);
3168     object_class_property_set_description(oc, "iommu",
3169                                           "Set the IOMMU type. "
3170                                           "Valid values are none and smmuv3");
3171 
3172     object_class_property_add_bool(oc, "default-bus-bypass-iommu",
3173                                    virt_get_default_bus_bypass_iommu,
3174                                    virt_set_default_bus_bypass_iommu);
3175     object_class_property_set_description(oc, "default-bus-bypass-iommu",
3176                                           "Set on/off to enable/disable "
3177                                           "bypass_iommu for default root bus");
3178 
3179     object_class_property_add_bool(oc, "ras", virt_get_ras,
3180                                    virt_set_ras);
3181     object_class_property_set_description(oc, "ras",
3182                                           "Set on/off to enable/disable reporting host memory errors "
3183                                           "to a KVM guest using ACPI and guest external abort exceptions");
3184 
3185     object_class_property_add_bool(oc, "mte", virt_get_mte, virt_set_mte);
3186     object_class_property_set_description(oc, "mte",
3187                                           "Set on/off to enable/disable emulating a "
3188                                           "guest CPU which implements the ARM "
3189                                           "Memory Tagging Extension");
3190 
3191     object_class_property_add_bool(oc, "its", virt_get_its,
3192                                    virt_set_its);
3193     object_class_property_set_description(oc, "its",
3194                                           "Set on/off to enable/disable "
3195                                           "ITS instantiation");
3196 
3197     object_class_property_add_bool(oc, "dtb-randomness",
3198                                    virt_get_dtb_randomness,
3199                                    virt_set_dtb_randomness);
3200     object_class_property_set_description(oc, "dtb-randomness",
3201                                           "Set off to disable passing random or "
3202                                           "non-deterministic dtb nodes to guest");
3203 
3204     object_class_property_add_bool(oc, "dtb-kaslr-seed",
3205                                    virt_get_dtb_randomness,
3206                                    virt_set_dtb_randomness);
3207     object_class_property_set_description(oc, "dtb-kaslr-seed",
3208                                           "Deprecated synonym of dtb-randomness");
3209 
3210     object_class_property_add_str(oc, "x-oem-id",
3211                                   virt_get_oem_id,
3212                                   virt_set_oem_id);
3213     object_class_property_set_description(oc, "x-oem-id",
3214                                           "Override the default value of field OEMID "
3215                                           "in ACPI table header."
3216                                           "The string may be up to 6 bytes in size");
3217 
3218 
3219     object_class_property_add_str(oc, "x-oem-table-id",
3220                                   virt_get_oem_table_id,
3221                                   virt_set_oem_table_id);
3222     object_class_property_set_description(oc, "x-oem-table-id",
3223                                           "Override the default value of field OEM Table ID "
3224                                           "in ACPI table header."
3225                                           "The string may be up to 8 bytes in size");
3226 
3227 }
3228 
3229 static void virt_instance_init(Object *obj)
3230 {
3231     VirtMachineState *vms = VIRT_MACHINE(obj);
3232     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
3233 
3234     /* EL3 is disabled by default on virt: this makes us consistent
3235      * between KVM and TCG for this board, and it also allows us to
3236      * boot UEFI blobs which assume no TrustZone support.
3237      */
3238     vms->secure = false;
3239 
3240     /* EL2 is also disabled by default, for similar reasons */
3241     vms->virt = false;
3242 
3243     /* High memory is enabled by default */
3244     vms->highmem = true;
3245     vms->highmem_compact = !vmc->no_highmem_compact;
3246     vms->gic_version = VIRT_GIC_VERSION_NOSEL;
3247 
3248     vms->highmem_ecam = !vmc->no_highmem_ecam;
3249     vms->highmem_mmio = true;
3250     vms->highmem_redists = true;
3251 
3252     if (vmc->no_its) {
3253         vms->its = false;
3254     } else {
3255         /* Default allows ITS instantiation */
3256         vms->its = true;
3257 
3258         if (vmc->no_tcg_its) {
3259             vms->tcg_its = false;
3260         } else {
3261             vms->tcg_its = true;
3262         }
3263     }
3264 
3265     /* Default disallows iommu instantiation */
3266     vms->iommu = VIRT_IOMMU_NONE;
3267 
3268     /* The default root bus is attached to iommu by default */
3269     vms->default_bus_bypass_iommu = false;
3270 
3271     /* Default disallows RAS instantiation */
3272     vms->ras = false;
3273 
3274     /* MTE is disabled by default.  */
3275     vms->mte = false;
3276 
3277     /* Supply kaslr-seed and rng-seed by default */
3278     vms->dtb_randomness = true;
3279 
3280     vms->irqmap = a15irqmap;
3281 
3282     virt_flash_create(vms);
3283 
3284     vms->oem_id = g_strndup(ACPI_BUILD_APPNAME6, 6);
3285     vms->oem_table_id = g_strndup(ACPI_BUILD_APPNAME8, 8);
3286 }
3287 
3288 static const TypeInfo virt_machine_info = {
3289     .name          = TYPE_VIRT_MACHINE,
3290     .parent        = TYPE_MACHINE,
3291     .abstract      = true,
3292     .instance_size = sizeof(VirtMachineState),
3293     .class_size    = sizeof(VirtMachineClass),
3294     .class_init    = virt_machine_class_init,
3295     .instance_init = virt_instance_init,
3296     .interfaces = (InterfaceInfo[]) {
3297          { TYPE_HOTPLUG_HANDLER },
3298          { }
3299     },
3300 };
3301 
3302 static void machvirt_machine_init(void)
3303 {
3304     type_register_static(&virt_machine_info);
3305 }
3306 type_init(machvirt_machine_init);
3307 
3308 static void virt_machine_9_2_options(MachineClass *mc)
3309 {
3310 }
3311 DEFINE_VIRT_MACHINE_AS_LATEST(9, 2)
3312 
3313 static void virt_machine_9_1_options(MachineClass *mc)
3314 {
3315     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3316 
3317     virt_machine_9_2_options(mc);
3318     compat_props_add(mc->compat_props, hw_compat_9_1, hw_compat_9_1_len);
3319     /* 9.1 and earlier have only a stage-1 SMMU, not a nested s1+2 one */
3320     vmc->no_nested_smmu = true;
3321 }
3322 DEFINE_VIRT_MACHINE(9, 1)
3323 
3324 static void virt_machine_9_0_options(MachineClass *mc)
3325 {
3326     virt_machine_9_1_options(mc);
3327     mc->smbios_memory_device_size = 16 * GiB;
3328     compat_props_add(mc->compat_props, hw_compat_9_0, hw_compat_9_0_len);
3329 }
3330 DEFINE_VIRT_MACHINE(9, 0)
3331 
3332 static void virt_machine_8_2_options(MachineClass *mc)
3333 {
3334     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3335 
3336     virt_machine_9_0_options(mc);
3337     compat_props_add(mc->compat_props, hw_compat_8_2, hw_compat_8_2_len);
3338     /*
3339      * Don't expose NS_EL2_VIRT timer IRQ in DTB on ACPI on 8.2 and
3340      * earlier machines. (Exposing it tickles a bug in older EDK2
3341      * guest BIOS binaries.)
3342      */
3343     vmc->no_ns_el2_virt_timer_irq = true;
3344 }
3345 DEFINE_VIRT_MACHINE(8, 2)
3346 
3347 static void virt_machine_8_1_options(MachineClass *mc)
3348 {
3349     virt_machine_8_2_options(mc);
3350     compat_props_add(mc->compat_props, hw_compat_8_1, hw_compat_8_1_len);
3351 }
3352 DEFINE_VIRT_MACHINE(8, 1)
3353 
3354 static void virt_machine_8_0_options(MachineClass *mc)
3355 {
3356     virt_machine_8_1_options(mc);
3357     compat_props_add(mc->compat_props, hw_compat_8_0, hw_compat_8_0_len);
3358 }
3359 DEFINE_VIRT_MACHINE(8, 0)
3360 
3361 static void virt_machine_7_2_options(MachineClass *mc)
3362 {
3363     virt_machine_8_0_options(mc);
3364     compat_props_add(mc->compat_props, hw_compat_7_2, hw_compat_7_2_len);
3365 }
3366 DEFINE_VIRT_MACHINE(7, 2)
3367 
3368 static void virt_machine_7_1_options(MachineClass *mc)
3369 {
3370     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3371 
3372     virt_machine_7_2_options(mc);
3373     compat_props_add(mc->compat_props, hw_compat_7_1, hw_compat_7_1_len);
3374     /* Compact layout for high memory regions was introduced with 7.2 */
3375     vmc->no_highmem_compact = true;
3376 }
3377 DEFINE_VIRT_MACHINE(7, 1)
3378 
3379 static void virt_machine_7_0_options(MachineClass *mc)
3380 {
3381     virt_machine_7_1_options(mc);
3382     compat_props_add(mc->compat_props, hw_compat_7_0, hw_compat_7_0_len);
3383 }
3384 DEFINE_VIRT_MACHINE(7, 0)
3385 
3386 static void virt_machine_6_2_options(MachineClass *mc)
3387 {
3388     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3389 
3390     virt_machine_7_0_options(mc);
3391     compat_props_add(mc->compat_props, hw_compat_6_2, hw_compat_6_2_len);
3392     vmc->no_tcg_lpa2 = true;
3393 }
3394 DEFINE_VIRT_MACHINE(6, 2)
3395 
3396 static void virt_machine_6_1_options(MachineClass *mc)
3397 {
3398     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3399 
3400     virt_machine_6_2_options(mc);
3401     compat_props_add(mc->compat_props, hw_compat_6_1, hw_compat_6_1_len);
3402     mc->smp_props.prefer_sockets = true;
3403     vmc->no_cpu_topology = true;
3404 
3405     /* qemu ITS was introduced with 6.2 */
3406     vmc->no_tcg_its = true;
3407 }
3408 DEFINE_VIRT_MACHINE(6, 1)
3409 
3410 static void virt_machine_6_0_options(MachineClass *mc)
3411 {
3412     virt_machine_6_1_options(mc);
3413     compat_props_add(mc->compat_props, hw_compat_6_0, hw_compat_6_0_len);
3414 }
3415 DEFINE_VIRT_MACHINE(6, 0)
3416 
3417 static void virt_machine_5_2_options(MachineClass *mc)
3418 {
3419     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3420 
3421     virt_machine_6_0_options(mc);
3422     compat_props_add(mc->compat_props, hw_compat_5_2, hw_compat_5_2_len);
3423     vmc->no_secure_gpio = true;
3424 }
3425 DEFINE_VIRT_MACHINE(5, 2)
3426 
3427 static void virt_machine_5_1_options(MachineClass *mc)
3428 {
3429     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3430 
3431     virt_machine_5_2_options(mc);
3432     compat_props_add(mc->compat_props, hw_compat_5_1, hw_compat_5_1_len);
3433     vmc->no_kvm_steal_time = true;
3434 }
3435 DEFINE_VIRT_MACHINE(5, 1)
3436 
3437 static void virt_machine_5_0_options(MachineClass *mc)
3438 {
3439     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3440 
3441     virt_machine_5_1_options(mc);
3442     compat_props_add(mc->compat_props, hw_compat_5_0, hw_compat_5_0_len);
3443     mc->numa_mem_supported = true;
3444     vmc->acpi_expose_flash = true;
3445     mc->auto_enable_numa_with_memdev = false;
3446 }
3447 DEFINE_VIRT_MACHINE(5, 0)
3448 
3449 static void virt_machine_4_2_options(MachineClass *mc)
3450 {
3451     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3452 
3453     virt_machine_5_0_options(mc);
3454     compat_props_add(mc->compat_props, hw_compat_4_2, hw_compat_4_2_len);
3455     vmc->kvm_no_adjvtime = true;
3456 }
3457 DEFINE_VIRT_MACHINE(4, 2)
3458 
3459 static void virt_machine_4_1_options(MachineClass *mc)
3460 {
3461     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3462 
3463     virt_machine_4_2_options(mc);
3464     compat_props_add(mc->compat_props, hw_compat_4_1, hw_compat_4_1_len);
3465     vmc->no_ged = true;
3466     mc->auto_enable_numa_with_memhp = false;
3467 }
3468 DEFINE_VIRT_MACHINE(4, 1)
3469 
3470 static void virt_machine_4_0_options(MachineClass *mc)
3471 {
3472     virt_machine_4_1_options(mc);
3473     compat_props_add(mc->compat_props, hw_compat_4_0, hw_compat_4_0_len);
3474 }
3475 DEFINE_VIRT_MACHINE(4, 0)
3476 
3477 static void virt_machine_3_1_options(MachineClass *mc)
3478 {
3479     virt_machine_4_0_options(mc);
3480     compat_props_add(mc->compat_props, hw_compat_3_1, hw_compat_3_1_len);
3481 }
3482 DEFINE_VIRT_MACHINE(3, 1)
3483 
3484 static void virt_machine_3_0_options(MachineClass *mc)
3485 {
3486     virt_machine_3_1_options(mc);
3487     compat_props_add(mc->compat_props, hw_compat_3_0, hw_compat_3_0_len);
3488 }
3489 DEFINE_VIRT_MACHINE(3, 0)
3490 
3491 static void virt_machine_2_12_options(MachineClass *mc)
3492 {
3493     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3494 
3495     virt_machine_3_0_options(mc);
3496     compat_props_add(mc->compat_props, hw_compat_2_12, hw_compat_2_12_len);
3497     vmc->no_highmem_ecam = true;
3498     mc->max_cpus = 255;
3499 }
3500 DEFINE_VIRT_MACHINE(2, 12)
3501 
3502 static void virt_machine_2_11_options(MachineClass *mc)
3503 {
3504     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3505 
3506     virt_machine_2_12_options(mc);
3507     compat_props_add(mc->compat_props, hw_compat_2_11, hw_compat_2_11_len);
3508     vmc->smbios_old_sys_ver = true;
3509 }
3510 DEFINE_VIRT_MACHINE(2, 11)
3511 
3512 static void virt_machine_2_10_options(MachineClass *mc)
3513 {
3514     virt_machine_2_11_options(mc);
3515     compat_props_add(mc->compat_props, hw_compat_2_10, hw_compat_2_10_len);
3516     /* before 2.11 we never faulted accesses to bad addresses */
3517     mc->ignore_memory_transaction_failures = true;
3518 }
3519 DEFINE_VIRT_MACHINE(2, 10)
3520 
3521 static void virt_machine_2_9_options(MachineClass *mc)
3522 {
3523     virt_machine_2_10_options(mc);
3524     compat_props_add(mc->compat_props, hw_compat_2_9, hw_compat_2_9_len);
3525 }
3526 DEFINE_VIRT_MACHINE(2, 9)
3527 
3528 static void virt_machine_2_8_options(MachineClass *mc)
3529 {
3530     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3531 
3532     virt_machine_2_9_options(mc);
3533     compat_props_add(mc->compat_props, hw_compat_2_8, hw_compat_2_8_len);
3534     /* For 2.8 and earlier we falsely claimed in the DT that
3535      * our timers were edge-triggered, not level-triggered.
3536      */
3537     vmc->claim_edge_triggered_timers = true;
3538 }
3539 DEFINE_VIRT_MACHINE(2, 8)
3540 
3541 static void virt_machine_2_7_options(MachineClass *mc)
3542 {
3543     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3544 
3545     virt_machine_2_8_options(mc);
3546     compat_props_add(mc->compat_props, hw_compat_2_7, hw_compat_2_7_len);
3547     /* ITS was introduced with 2.8 */
3548     vmc->no_its = true;
3549     /* Stick with 1K pages for migration compatibility */
3550     mc->minimum_page_bits = 0;
3551 }
3552 DEFINE_VIRT_MACHINE(2, 7)
3553 
3554 static void virt_machine_2_6_options(MachineClass *mc)
3555 {
3556     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
3557 
3558     virt_machine_2_7_options(mc);
3559     compat_props_add(mc->compat_props, hw_compat_2_6, hw_compat_2_6_len);
3560     vmc->disallow_affinity_adjustment = true;
3561     /* Disable PMU for 2.6 as PMU support was first introduced in 2.7 */
3562     vmc->no_pmu = true;
3563 }
3564 DEFINE_VIRT_MACHINE(2, 6)
3565