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