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