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