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