xref: /openbmc/qemu/hw/arm/virt.c (revision ad9e5aa2)
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-common.h"
33 #include "qemu/units.h"
34 #include "qemu/option.h"
35 #include "monitor/qdev.h"
36 #include "qapi/error.h"
37 #include "hw/sysbus.h"
38 #include "hw/boards.h"
39 #include "hw/arm/boot.h"
40 #include "hw/arm/primecell.h"
41 #include "hw/arm/virt.h"
42 #include "hw/block/flash.h"
43 #include "hw/vfio/vfio-calxeda-xgmac.h"
44 #include "hw/vfio/vfio-amd-xgbe.h"
45 #include "hw/display/ramfb.h"
46 #include "net/net.h"
47 #include "sysemu/device_tree.h"
48 #include "sysemu/numa.h"
49 #include "sysemu/runstate.h"
50 #include "sysemu/sysemu.h"
51 #include "sysemu/tpm.h"
52 #include "sysemu/kvm.h"
53 #include "hw/loader.h"
54 #include "exec/address-spaces.h"
55 #include "qemu/bitops.h"
56 #include "qemu/error-report.h"
57 #include "qemu/module.h"
58 #include "hw/pci-host/gpex.h"
59 #include "hw/virtio/virtio-pci.h"
60 #include "hw/arm/sysbus-fdt.h"
61 #include "hw/platform-bus.h"
62 #include "hw/qdev-properties.h"
63 #include "hw/arm/fdt.h"
64 #include "hw/intc/arm_gic.h"
65 #include "hw/intc/arm_gicv3_common.h"
66 #include "hw/irq.h"
67 #include "kvm_arm.h"
68 #include "hw/firmware/smbios.h"
69 #include "qapi/visitor.h"
70 #include "qapi/qapi-visit-common.h"
71 #include "standard-headers/linux/input.h"
72 #include "hw/arm/smmuv3.h"
73 #include "hw/acpi/acpi.h"
74 #include "target/arm/internals.h"
75 #include "hw/mem/pc-dimm.h"
76 #include "hw/mem/nvdimm.h"
77 #include "hw/acpi/generic_event_device.h"
78 #include "hw/virtio/virtio-iommu.h"
79 #include "hw/char/pl011.h"
80 #include "qemu/guest-random.h"
81 
82 #define DEFINE_VIRT_MACHINE_LATEST(major, minor, latest) \
83     static void virt_##major##_##minor##_class_init(ObjectClass *oc, \
84                                                     void *data) \
85     { \
86         MachineClass *mc = MACHINE_CLASS(oc); \
87         virt_machine_##major##_##minor##_options(mc); \
88         mc->desc = "QEMU " # major "." # minor " ARM Virtual Machine"; \
89         if (latest) { \
90             mc->alias = "virt"; \
91         } \
92     } \
93     static const TypeInfo machvirt_##major##_##minor##_info = { \
94         .name = MACHINE_TYPE_NAME("virt-" # major "." # minor), \
95         .parent = TYPE_VIRT_MACHINE, \
96         .class_init = virt_##major##_##minor##_class_init, \
97     }; \
98     static void machvirt_machine_##major##_##minor##_init(void) \
99     { \
100         type_register_static(&machvirt_##major##_##minor##_info); \
101     } \
102     type_init(machvirt_machine_##major##_##minor##_init);
103 
104 #define DEFINE_VIRT_MACHINE_AS_LATEST(major, minor) \
105     DEFINE_VIRT_MACHINE_LATEST(major, minor, true)
106 #define DEFINE_VIRT_MACHINE(major, minor) \
107     DEFINE_VIRT_MACHINE_LATEST(major, minor, false)
108 
109 
110 /* Number of external interrupt lines to configure the GIC with */
111 #define NUM_IRQS 256
112 
113 #define PLATFORM_BUS_NUM_IRQS 64
114 
115 /* Legacy RAM limit in GB (< version 4.0) */
116 #define LEGACY_RAMLIMIT_GB 255
117 #define LEGACY_RAMLIMIT_BYTES (LEGACY_RAMLIMIT_GB * GiB)
118 
119 /* Addresses and sizes of our components.
120  * 0..128MB is space for a flash device so we can run bootrom code such as UEFI.
121  * 128MB..256MB is used for miscellaneous device I/O.
122  * 256MB..1GB is reserved for possible future PCI support (ie where the
123  * PCI memory window will go if we add a PCI host controller).
124  * 1GB and up is RAM (which may happily spill over into the
125  * high memory region beyond 4GB).
126  * This represents a compromise between how much RAM can be given to
127  * a 32 bit VM and leaving space for expansion and in particular for PCI.
128  * Note that devices should generally be placed at multiples of 0x10000,
129  * to accommodate guests using 64K pages.
130  */
131 static const MemMapEntry base_memmap[] = {
132     /* Space up to 0x8000000 is reserved for a boot ROM */
133     [VIRT_FLASH] =              {          0, 0x08000000 },
134     [VIRT_CPUPERIPHS] =         { 0x08000000, 0x00020000 },
135     /* GIC distributor and CPU interfaces sit inside the CPU peripheral space */
136     [VIRT_GIC_DIST] =           { 0x08000000, 0x00010000 },
137     [VIRT_GIC_CPU] =            { 0x08010000, 0x00010000 },
138     [VIRT_GIC_V2M] =            { 0x08020000, 0x00001000 },
139     [VIRT_GIC_HYP] =            { 0x08030000, 0x00010000 },
140     [VIRT_GIC_VCPU] =           { 0x08040000, 0x00010000 },
141     /* The space in between here is reserved for GICv3 CPU/vCPU/HYP */
142     [VIRT_GIC_ITS] =            { 0x08080000, 0x00020000 },
143     /* This redistributor space allows up to 2*64kB*123 CPUs */
144     [VIRT_GIC_REDIST] =         { 0x080A0000, 0x00F60000 },
145     [VIRT_UART] =               { 0x09000000, 0x00001000 },
146     [VIRT_RTC] =                { 0x09010000, 0x00001000 },
147     [VIRT_FW_CFG] =             { 0x09020000, 0x00000018 },
148     [VIRT_GPIO] =               { 0x09030000, 0x00001000 },
149     [VIRT_SECURE_UART] =        { 0x09040000, 0x00001000 },
150     [VIRT_SMMU] =               { 0x09050000, 0x00020000 },
151     [VIRT_PCDIMM_ACPI] =        { 0x09070000, MEMORY_HOTPLUG_IO_LEN },
152     [VIRT_ACPI_GED] =           { 0x09080000, ACPI_GED_EVT_SEL_LEN },
153     [VIRT_NVDIMM_ACPI] =        { 0x09090000, NVDIMM_ACPI_IO_LEN},
154     [VIRT_MMIO] =               { 0x0a000000, 0x00000200 },
155     /* ...repeating for a total of NUM_VIRTIO_TRANSPORTS, each of that size */
156     [VIRT_PLATFORM_BUS] =       { 0x0c000000, 0x02000000 },
157     [VIRT_SECURE_MEM] =         { 0x0e000000, 0x01000000 },
158     [VIRT_PCIE_MMIO] =          { 0x10000000, 0x2eff0000 },
159     [VIRT_PCIE_PIO] =           { 0x3eff0000, 0x00010000 },
160     [VIRT_PCIE_ECAM] =          { 0x3f000000, 0x01000000 },
161     /* Actual RAM size depends on initial RAM and device memory settings */
162     [VIRT_MEM] =                { GiB, LEGACY_RAMLIMIT_BYTES },
163 };
164 
165 /*
166  * Highmem IO Regions: This memory map is floating, located after the RAM.
167  * Each MemMapEntry base (GPA) will be dynamically computed, depending on the
168  * top of the RAM, so that its base get the same alignment as the size,
169  * ie. a 512GiB entry will be aligned on a 512GiB boundary. If there is
170  * less than 256GiB of RAM, the floating area starts at the 256GiB mark.
171  * Note the extended_memmap is sized so that it eventually also includes the
172  * base_memmap entries (VIRT_HIGH_GIC_REDIST2 index is greater than the last
173  * index of base_memmap).
174  */
175 static MemMapEntry extended_memmap[] = {
176     /* Additional 64 MB redist region (can contain up to 512 redistributors) */
177     [VIRT_HIGH_GIC_REDIST2] =   { 0x0, 64 * MiB },
178     [VIRT_HIGH_PCIE_ECAM] =     { 0x0, 256 * MiB },
179     /* Second PCIe window */
180     [VIRT_HIGH_PCIE_MMIO] =     { 0x0, 512 * GiB },
181 };
182 
183 static const int a15irqmap[] = {
184     [VIRT_UART] = 1,
185     [VIRT_RTC] = 2,
186     [VIRT_PCIE] = 3, /* ... to 6 */
187     [VIRT_GPIO] = 7,
188     [VIRT_SECURE_UART] = 8,
189     [VIRT_ACPI_GED] = 9,
190     [VIRT_MMIO] = 16, /* ...to 16 + NUM_VIRTIO_TRANSPORTS - 1 */
191     [VIRT_GIC_V2M] = 48, /* ...to 48 + NUM_GICV2M_SPIS - 1 */
192     [VIRT_SMMU] = 74,    /* ...to 74 + NUM_SMMU_IRQS - 1 */
193     [VIRT_PLATFORM_BUS] = 112, /* ...to 112 + PLATFORM_BUS_NUM_IRQS -1 */
194 };
195 
196 static const char *valid_cpus[] = {
197     ARM_CPU_TYPE_NAME("cortex-a7"),
198     ARM_CPU_TYPE_NAME("cortex-a15"),
199     ARM_CPU_TYPE_NAME("cortex-a53"),
200     ARM_CPU_TYPE_NAME("cortex-a57"),
201     ARM_CPU_TYPE_NAME("cortex-a72"),
202     ARM_CPU_TYPE_NAME("host"),
203     ARM_CPU_TYPE_NAME("max"),
204 };
205 
206 static bool cpu_type_valid(const char *cpu)
207 {
208     int i;
209 
210     for (i = 0; i < ARRAY_SIZE(valid_cpus); i++) {
211         if (strcmp(cpu, valid_cpus[i]) == 0) {
212             return true;
213         }
214     }
215     return false;
216 }
217 
218 static void create_kaslr_seed(VirtMachineState *vms, const char *node)
219 {
220     uint64_t seed;
221 
222     if (qemu_guest_getrandom(&seed, sizeof(seed), NULL)) {
223         return;
224     }
225     qemu_fdt_setprop_u64(vms->fdt, node, "kaslr-seed", seed);
226 }
227 
228 static void create_fdt(VirtMachineState *vms)
229 {
230     MachineState *ms = MACHINE(vms);
231     int nb_numa_nodes = ms->numa_state->num_nodes;
232     void *fdt = create_device_tree(&vms->fdt_size);
233 
234     if (!fdt) {
235         error_report("create_device_tree() failed");
236         exit(1);
237     }
238 
239     vms->fdt = fdt;
240 
241     /* Header */
242     qemu_fdt_setprop_string(fdt, "/", "compatible", "linux,dummy-virt");
243     qemu_fdt_setprop_cell(fdt, "/", "#address-cells", 0x2);
244     qemu_fdt_setprop_cell(fdt, "/", "#size-cells", 0x2);
245 
246     /* /chosen must exist for load_dtb to fill in necessary properties later */
247     qemu_fdt_add_subnode(fdt, "/chosen");
248     create_kaslr_seed(vms, "/chosen");
249 
250     if (vms->secure) {
251         qemu_fdt_add_subnode(fdt, "/secure-chosen");
252         create_kaslr_seed(vms, "/secure-chosen");
253     }
254 
255     /* Clock node, for the benefit of the UART. The kernel device tree
256      * binding documentation claims the PL011 node clock properties are
257      * optional but in practice if you omit them the kernel refuses to
258      * probe for the device.
259      */
260     vms->clock_phandle = qemu_fdt_alloc_phandle(fdt);
261     qemu_fdt_add_subnode(fdt, "/apb-pclk");
262     qemu_fdt_setprop_string(fdt, "/apb-pclk", "compatible", "fixed-clock");
263     qemu_fdt_setprop_cell(fdt, "/apb-pclk", "#clock-cells", 0x0);
264     qemu_fdt_setprop_cell(fdt, "/apb-pclk", "clock-frequency", 24000000);
265     qemu_fdt_setprop_string(fdt, "/apb-pclk", "clock-output-names",
266                                 "clk24mhz");
267     qemu_fdt_setprop_cell(fdt, "/apb-pclk", "phandle", vms->clock_phandle);
268 
269     if (nb_numa_nodes > 0 && ms->numa_state->have_numa_distance) {
270         int size = nb_numa_nodes * nb_numa_nodes * 3 * sizeof(uint32_t);
271         uint32_t *matrix = g_malloc0(size);
272         int idx, i, j;
273 
274         for (i = 0; i < nb_numa_nodes; i++) {
275             for (j = 0; j < nb_numa_nodes; j++) {
276                 idx = (i * nb_numa_nodes + j) * 3;
277                 matrix[idx + 0] = cpu_to_be32(i);
278                 matrix[idx + 1] = cpu_to_be32(j);
279                 matrix[idx + 2] =
280                     cpu_to_be32(ms->numa_state->nodes[i].distance[j]);
281             }
282         }
283 
284         qemu_fdt_add_subnode(fdt, "/distance-map");
285         qemu_fdt_setprop_string(fdt, "/distance-map", "compatible",
286                                 "numa-distance-map-v1");
287         qemu_fdt_setprop(fdt, "/distance-map", "distance-matrix",
288                          matrix, size);
289         g_free(matrix);
290     }
291 }
292 
293 static void fdt_add_timer_nodes(const VirtMachineState *vms)
294 {
295     /* On real hardware these interrupts are level-triggered.
296      * On KVM they were edge-triggered before host kernel version 4.4,
297      * and level-triggered afterwards.
298      * On emulated QEMU they are level-triggered.
299      *
300      * Getting the DTB info about them wrong is awkward for some
301      * guest kernels:
302      *  pre-4.8 ignore the DT and leave the interrupt configured
303      *   with whatever the GIC reset value (or the bootloader) left it at
304      *  4.8 before rc6 honour the incorrect data by programming it back
305      *   into the GIC, causing problems
306      *  4.8rc6 and later ignore the DT and always write "level triggered"
307      *   into the GIC
308      *
309      * For backwards-compatibility, virt-2.8 and earlier will continue
310      * to say these are edge-triggered, but later machines will report
311      * the correct information.
312      */
313     ARMCPU *armcpu;
314     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
315     uint32_t irqflags = GIC_FDT_IRQ_FLAGS_LEVEL_HI;
316 
317     if (vmc->claim_edge_triggered_timers) {
318         irqflags = GIC_FDT_IRQ_FLAGS_EDGE_LO_HI;
319     }
320 
321     if (vms->gic_version == VIRT_GIC_VERSION_2) {
322         irqflags = deposit32(irqflags, GIC_FDT_IRQ_PPI_CPU_START,
323                              GIC_FDT_IRQ_PPI_CPU_WIDTH,
324                              (1 << vms->smp_cpus) - 1);
325     }
326 
327     qemu_fdt_add_subnode(vms->fdt, "/timer");
328 
329     armcpu = ARM_CPU(qemu_get_cpu(0));
330     if (arm_feature(&armcpu->env, ARM_FEATURE_V8)) {
331         const char compat[] = "arm,armv8-timer\0arm,armv7-timer";
332         qemu_fdt_setprop(vms->fdt, "/timer", "compatible",
333                          compat, sizeof(compat));
334     } else {
335         qemu_fdt_setprop_string(vms->fdt, "/timer", "compatible",
336                                 "arm,armv7-timer");
337     }
338     qemu_fdt_setprop(vms->fdt, "/timer", "always-on", NULL, 0);
339     qemu_fdt_setprop_cells(vms->fdt, "/timer", "interrupts",
340                        GIC_FDT_IRQ_TYPE_PPI, ARCH_TIMER_S_EL1_IRQ, irqflags,
341                        GIC_FDT_IRQ_TYPE_PPI, ARCH_TIMER_NS_EL1_IRQ, irqflags,
342                        GIC_FDT_IRQ_TYPE_PPI, ARCH_TIMER_VIRT_IRQ, irqflags,
343                        GIC_FDT_IRQ_TYPE_PPI, ARCH_TIMER_NS_EL2_IRQ, irqflags);
344 }
345 
346 static void fdt_add_cpu_nodes(const VirtMachineState *vms)
347 {
348     int cpu;
349     int addr_cells = 1;
350     const MachineState *ms = MACHINE(vms);
351 
352     /*
353      * From Documentation/devicetree/bindings/arm/cpus.txt
354      *  On ARM v8 64-bit systems value should be set to 2,
355      *  that corresponds to the MPIDR_EL1 register size.
356      *  If MPIDR_EL1[63:32] value is equal to 0 on all CPUs
357      *  in the system, #address-cells can be set to 1, since
358      *  MPIDR_EL1[63:32] bits are not used for CPUs
359      *  identification.
360      *
361      *  Here we actually don't know whether our system is 32- or 64-bit one.
362      *  The simplest way to go is to examine affinity IDs of all our CPUs. If
363      *  at least one of them has Aff3 populated, we set #address-cells to 2.
364      */
365     for (cpu = 0; cpu < vms->smp_cpus; cpu++) {
366         ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(cpu));
367 
368         if (armcpu->mp_affinity & ARM_AFF3_MASK) {
369             addr_cells = 2;
370             break;
371         }
372     }
373 
374     qemu_fdt_add_subnode(vms->fdt, "/cpus");
375     qemu_fdt_setprop_cell(vms->fdt, "/cpus", "#address-cells", addr_cells);
376     qemu_fdt_setprop_cell(vms->fdt, "/cpus", "#size-cells", 0x0);
377 
378     for (cpu = vms->smp_cpus - 1; cpu >= 0; cpu--) {
379         char *nodename = g_strdup_printf("/cpus/cpu@%d", cpu);
380         ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(cpu));
381         CPUState *cs = CPU(armcpu);
382 
383         qemu_fdt_add_subnode(vms->fdt, nodename);
384         qemu_fdt_setprop_string(vms->fdt, nodename, "device_type", "cpu");
385         qemu_fdt_setprop_string(vms->fdt, nodename, "compatible",
386                                     armcpu->dtb_compatible);
387 
388         if (vms->psci_conduit != QEMU_PSCI_CONDUIT_DISABLED
389             && vms->smp_cpus > 1) {
390             qemu_fdt_setprop_string(vms->fdt, nodename,
391                                         "enable-method", "psci");
392         }
393 
394         if (addr_cells == 2) {
395             qemu_fdt_setprop_u64(vms->fdt, nodename, "reg",
396                                  armcpu->mp_affinity);
397         } else {
398             qemu_fdt_setprop_cell(vms->fdt, nodename, "reg",
399                                   armcpu->mp_affinity);
400         }
401 
402         if (ms->possible_cpus->cpus[cs->cpu_index].props.has_node_id) {
403             qemu_fdt_setprop_cell(vms->fdt, nodename, "numa-node-id",
404                 ms->possible_cpus->cpus[cs->cpu_index].props.node_id);
405         }
406 
407         g_free(nodename);
408     }
409 }
410 
411 static void fdt_add_its_gic_node(VirtMachineState *vms)
412 {
413     char *nodename;
414 
415     vms->msi_phandle = qemu_fdt_alloc_phandle(vms->fdt);
416     nodename = g_strdup_printf("/intc/its@%" PRIx64,
417                                vms->memmap[VIRT_GIC_ITS].base);
418     qemu_fdt_add_subnode(vms->fdt, nodename);
419     qemu_fdt_setprop_string(vms->fdt, nodename, "compatible",
420                             "arm,gic-v3-its");
421     qemu_fdt_setprop(vms->fdt, nodename, "msi-controller", NULL, 0);
422     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
423                                  2, vms->memmap[VIRT_GIC_ITS].base,
424                                  2, vms->memmap[VIRT_GIC_ITS].size);
425     qemu_fdt_setprop_cell(vms->fdt, nodename, "phandle", vms->msi_phandle);
426     g_free(nodename);
427 }
428 
429 static void fdt_add_v2m_gic_node(VirtMachineState *vms)
430 {
431     char *nodename;
432 
433     nodename = g_strdup_printf("/intc/v2m@%" PRIx64,
434                                vms->memmap[VIRT_GIC_V2M].base);
435     vms->msi_phandle = qemu_fdt_alloc_phandle(vms->fdt);
436     qemu_fdt_add_subnode(vms->fdt, nodename);
437     qemu_fdt_setprop_string(vms->fdt, nodename, "compatible",
438                             "arm,gic-v2m-frame");
439     qemu_fdt_setprop(vms->fdt, nodename, "msi-controller", NULL, 0);
440     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
441                                  2, vms->memmap[VIRT_GIC_V2M].base,
442                                  2, vms->memmap[VIRT_GIC_V2M].size);
443     qemu_fdt_setprop_cell(vms->fdt, nodename, "phandle", vms->msi_phandle);
444     g_free(nodename);
445 }
446 
447 static void fdt_add_gic_node(VirtMachineState *vms)
448 {
449     char *nodename;
450 
451     vms->gic_phandle = qemu_fdt_alloc_phandle(vms->fdt);
452     qemu_fdt_setprop_cell(vms->fdt, "/", "interrupt-parent", vms->gic_phandle);
453 
454     nodename = g_strdup_printf("/intc@%" PRIx64,
455                                vms->memmap[VIRT_GIC_DIST].base);
456     qemu_fdt_add_subnode(vms->fdt, nodename);
457     qemu_fdt_setprop_cell(vms->fdt, nodename, "#interrupt-cells", 3);
458     qemu_fdt_setprop(vms->fdt, nodename, "interrupt-controller", NULL, 0);
459     qemu_fdt_setprop_cell(vms->fdt, nodename, "#address-cells", 0x2);
460     qemu_fdt_setprop_cell(vms->fdt, nodename, "#size-cells", 0x2);
461     qemu_fdt_setprop(vms->fdt, nodename, "ranges", NULL, 0);
462     if (vms->gic_version == VIRT_GIC_VERSION_3) {
463         int nb_redist_regions = virt_gicv3_redist_region_count(vms);
464 
465         qemu_fdt_setprop_string(vms->fdt, nodename, "compatible",
466                                 "arm,gic-v3");
467 
468         qemu_fdt_setprop_cell(vms->fdt, nodename,
469                               "#redistributor-regions", nb_redist_regions);
470 
471         if (nb_redist_regions == 1) {
472             qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
473                                          2, vms->memmap[VIRT_GIC_DIST].base,
474                                          2, vms->memmap[VIRT_GIC_DIST].size,
475                                          2, vms->memmap[VIRT_GIC_REDIST].base,
476                                          2, vms->memmap[VIRT_GIC_REDIST].size);
477         } else {
478             qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
479                                  2, vms->memmap[VIRT_GIC_DIST].base,
480                                  2, vms->memmap[VIRT_GIC_DIST].size,
481                                  2, vms->memmap[VIRT_GIC_REDIST].base,
482                                  2, vms->memmap[VIRT_GIC_REDIST].size,
483                                  2, vms->memmap[VIRT_HIGH_GIC_REDIST2].base,
484                                  2, vms->memmap[VIRT_HIGH_GIC_REDIST2].size);
485         }
486 
487         if (vms->virt) {
488             qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupts",
489                                    GIC_FDT_IRQ_TYPE_PPI, ARCH_GIC_MAINT_IRQ,
490                                    GIC_FDT_IRQ_FLAGS_LEVEL_HI);
491         }
492     } else {
493         /* 'cortex-a15-gic' means 'GIC v2' */
494         qemu_fdt_setprop_string(vms->fdt, nodename, "compatible",
495                                 "arm,cortex-a15-gic");
496         if (!vms->virt) {
497             qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
498                                          2, vms->memmap[VIRT_GIC_DIST].base,
499                                          2, vms->memmap[VIRT_GIC_DIST].size,
500                                          2, vms->memmap[VIRT_GIC_CPU].base,
501                                          2, vms->memmap[VIRT_GIC_CPU].size);
502         } else {
503             qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
504                                          2, vms->memmap[VIRT_GIC_DIST].base,
505                                          2, vms->memmap[VIRT_GIC_DIST].size,
506                                          2, vms->memmap[VIRT_GIC_CPU].base,
507                                          2, vms->memmap[VIRT_GIC_CPU].size,
508                                          2, vms->memmap[VIRT_GIC_HYP].base,
509                                          2, vms->memmap[VIRT_GIC_HYP].size,
510                                          2, vms->memmap[VIRT_GIC_VCPU].base,
511                                          2, vms->memmap[VIRT_GIC_VCPU].size);
512             qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupts",
513                                    GIC_FDT_IRQ_TYPE_PPI, ARCH_GIC_MAINT_IRQ,
514                                    GIC_FDT_IRQ_FLAGS_LEVEL_HI);
515         }
516     }
517 
518     qemu_fdt_setprop_cell(vms->fdt, nodename, "phandle", vms->gic_phandle);
519     g_free(nodename);
520 }
521 
522 static void fdt_add_pmu_nodes(const VirtMachineState *vms)
523 {
524     CPUState *cpu;
525     ARMCPU *armcpu;
526     uint32_t irqflags = GIC_FDT_IRQ_FLAGS_LEVEL_HI;
527 
528     CPU_FOREACH(cpu) {
529         armcpu = ARM_CPU(cpu);
530         if (!arm_feature(&armcpu->env, ARM_FEATURE_PMU)) {
531             return;
532         }
533         if (kvm_enabled()) {
534             if (kvm_irqchip_in_kernel()) {
535                 kvm_arm_pmu_set_irq(cpu, PPI(VIRTUAL_PMU_IRQ));
536             }
537             kvm_arm_pmu_init(cpu);
538         }
539     }
540 
541     if (vms->gic_version == VIRT_GIC_VERSION_2) {
542         irqflags = deposit32(irqflags, GIC_FDT_IRQ_PPI_CPU_START,
543                              GIC_FDT_IRQ_PPI_CPU_WIDTH,
544                              (1 << vms->smp_cpus) - 1);
545     }
546 
547     armcpu = ARM_CPU(qemu_get_cpu(0));
548     qemu_fdt_add_subnode(vms->fdt, "/pmu");
549     if (arm_feature(&armcpu->env, ARM_FEATURE_V8)) {
550         const char compat[] = "arm,armv8-pmuv3";
551         qemu_fdt_setprop(vms->fdt, "/pmu", "compatible",
552                          compat, sizeof(compat));
553         qemu_fdt_setprop_cells(vms->fdt, "/pmu", "interrupts",
554                                GIC_FDT_IRQ_TYPE_PPI, VIRTUAL_PMU_IRQ, irqflags);
555     }
556 }
557 
558 static inline DeviceState *create_acpi_ged(VirtMachineState *vms)
559 {
560     DeviceState *dev;
561     MachineState *ms = MACHINE(vms);
562     int irq = vms->irqmap[VIRT_ACPI_GED];
563     uint32_t event = ACPI_GED_PWR_DOWN_EVT;
564 
565     if (ms->ram_slots) {
566         event |= ACPI_GED_MEM_HOTPLUG_EVT;
567     }
568 
569     if (ms->nvdimms_state->is_enabled) {
570         event |= ACPI_GED_NVDIMM_HOTPLUG_EVT;
571     }
572 
573     dev = qdev_new(TYPE_ACPI_GED);
574     qdev_prop_set_uint32(dev, "ged-event", event);
575 
576     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VIRT_ACPI_GED].base);
577     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 1, vms->memmap[VIRT_PCDIMM_ACPI].base);
578     sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, qdev_get_gpio_in(vms->gic, irq));
579 
580     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
581 
582     return dev;
583 }
584 
585 static void create_its(VirtMachineState *vms)
586 {
587     const char *itsclass = its_class_name();
588     DeviceState *dev;
589 
590     if (!itsclass) {
591         /* Do nothing if not supported */
592         return;
593     }
594 
595     dev = qdev_new(itsclass);
596 
597     object_property_set_link(OBJECT(dev), OBJECT(vms->gic), "parent-gicv3",
598                              &error_abort);
599     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
600     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VIRT_GIC_ITS].base);
601 
602     fdt_add_its_gic_node(vms);
603 }
604 
605 static void create_v2m(VirtMachineState *vms)
606 {
607     int i;
608     int irq = vms->irqmap[VIRT_GIC_V2M];
609     DeviceState *dev;
610 
611     dev = qdev_new("arm-gicv2m");
612     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VIRT_GIC_V2M].base);
613     qdev_prop_set_uint32(dev, "base-spi", irq);
614     qdev_prop_set_uint32(dev, "num-spi", NUM_GICV2M_SPIS);
615     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
616 
617     for (i = 0; i < NUM_GICV2M_SPIS; i++) {
618         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
619                            qdev_get_gpio_in(vms->gic, irq + i));
620     }
621 
622     fdt_add_v2m_gic_node(vms);
623 }
624 
625 static void create_gic(VirtMachineState *vms)
626 {
627     MachineState *ms = MACHINE(vms);
628     /* We create a standalone GIC */
629     SysBusDevice *gicbusdev;
630     const char *gictype;
631     int type = vms->gic_version, i;
632     unsigned int smp_cpus = ms->smp.cpus;
633     uint32_t nb_redist_regions = 0;
634 
635     gictype = (type == 3) ? gicv3_class_name() : gic_class_name();
636 
637     vms->gic = qdev_new(gictype);
638     qdev_prop_set_uint32(vms->gic, "revision", type);
639     qdev_prop_set_uint32(vms->gic, "num-cpu", smp_cpus);
640     /* Note that the num-irq property counts both internal and external
641      * interrupts; there are always 32 of the former (mandated by GIC spec).
642      */
643     qdev_prop_set_uint32(vms->gic, "num-irq", NUM_IRQS + 32);
644     if (!kvm_irqchip_in_kernel()) {
645         qdev_prop_set_bit(vms->gic, "has-security-extensions", vms->secure);
646     }
647 
648     if (type == 3) {
649         uint32_t redist0_capacity =
650                     vms->memmap[VIRT_GIC_REDIST].size / GICV3_REDIST_SIZE;
651         uint32_t redist0_count = MIN(smp_cpus, redist0_capacity);
652 
653         nb_redist_regions = virt_gicv3_redist_region_count(vms);
654 
655         qdev_prop_set_uint32(vms->gic, "len-redist-region-count",
656                              nb_redist_regions);
657         qdev_prop_set_uint32(vms->gic, "redist-region-count[0]", redist0_count);
658 
659         if (nb_redist_regions == 2) {
660             uint32_t redist1_capacity =
661                     vms->memmap[VIRT_HIGH_GIC_REDIST2].size / GICV3_REDIST_SIZE;
662 
663             qdev_prop_set_uint32(vms->gic, "redist-region-count[1]",
664                 MIN(smp_cpus - redist0_count, redist1_capacity));
665         }
666     } else {
667         if (!kvm_irqchip_in_kernel()) {
668             qdev_prop_set_bit(vms->gic, "has-virtualization-extensions",
669                               vms->virt);
670         }
671     }
672     gicbusdev = SYS_BUS_DEVICE(vms->gic);
673     sysbus_realize_and_unref(gicbusdev, &error_fatal);
674     sysbus_mmio_map(gicbusdev, 0, vms->memmap[VIRT_GIC_DIST].base);
675     if (type == 3) {
676         sysbus_mmio_map(gicbusdev, 1, vms->memmap[VIRT_GIC_REDIST].base);
677         if (nb_redist_regions == 2) {
678             sysbus_mmio_map(gicbusdev, 2,
679                             vms->memmap[VIRT_HIGH_GIC_REDIST2].base);
680         }
681     } else {
682         sysbus_mmio_map(gicbusdev, 1, vms->memmap[VIRT_GIC_CPU].base);
683         if (vms->virt) {
684             sysbus_mmio_map(gicbusdev, 2, vms->memmap[VIRT_GIC_HYP].base);
685             sysbus_mmio_map(gicbusdev, 3, vms->memmap[VIRT_GIC_VCPU].base);
686         }
687     }
688 
689     /* Wire the outputs from each CPU's generic timer and the GICv3
690      * maintenance interrupt signal to the appropriate GIC PPI inputs,
691      * and the GIC's IRQ/FIQ/VIRQ/VFIQ interrupt outputs to the CPU's inputs.
692      */
693     for (i = 0; i < smp_cpus; i++) {
694         DeviceState *cpudev = DEVICE(qemu_get_cpu(i));
695         int ppibase = NUM_IRQS + i * GIC_INTERNAL + GIC_NR_SGIS;
696         int irq;
697         /* Mapping from the output timer irq lines from the CPU to the
698          * GIC PPI inputs we use for the virt board.
699          */
700         const int timer_irq[] = {
701             [GTIMER_PHYS] = ARCH_TIMER_NS_EL1_IRQ,
702             [GTIMER_VIRT] = ARCH_TIMER_VIRT_IRQ,
703             [GTIMER_HYP]  = ARCH_TIMER_NS_EL2_IRQ,
704             [GTIMER_SEC]  = ARCH_TIMER_S_EL1_IRQ,
705         };
706 
707         for (irq = 0; irq < ARRAY_SIZE(timer_irq); irq++) {
708             qdev_connect_gpio_out(cpudev, irq,
709                                   qdev_get_gpio_in(vms->gic,
710                                                    ppibase + timer_irq[irq]));
711         }
712 
713         if (type == 3) {
714             qemu_irq irq = qdev_get_gpio_in(vms->gic,
715                                             ppibase + ARCH_GIC_MAINT_IRQ);
716             qdev_connect_gpio_out_named(cpudev, "gicv3-maintenance-interrupt",
717                                         0, irq);
718         } else if (vms->virt) {
719             qemu_irq irq = qdev_get_gpio_in(vms->gic,
720                                             ppibase + ARCH_GIC_MAINT_IRQ);
721             sysbus_connect_irq(gicbusdev, i + 4 * smp_cpus, irq);
722         }
723 
724         qdev_connect_gpio_out_named(cpudev, "pmu-interrupt", 0,
725                                     qdev_get_gpio_in(vms->gic, ppibase
726                                                      + VIRTUAL_PMU_IRQ));
727 
728         sysbus_connect_irq(gicbusdev, i, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ));
729         sysbus_connect_irq(gicbusdev, i + smp_cpus,
730                            qdev_get_gpio_in(cpudev, ARM_CPU_FIQ));
731         sysbus_connect_irq(gicbusdev, i + 2 * smp_cpus,
732                            qdev_get_gpio_in(cpudev, ARM_CPU_VIRQ));
733         sysbus_connect_irq(gicbusdev, i + 3 * smp_cpus,
734                            qdev_get_gpio_in(cpudev, ARM_CPU_VFIQ));
735     }
736 
737     fdt_add_gic_node(vms);
738 
739     if (type == 3 && vms->its) {
740         create_its(vms);
741     } else if (type == 2) {
742         create_v2m(vms);
743     }
744 }
745 
746 static void create_uart(const VirtMachineState *vms, int uart,
747                         MemoryRegion *mem, Chardev *chr)
748 {
749     char *nodename;
750     hwaddr base = vms->memmap[uart].base;
751     hwaddr size = vms->memmap[uart].size;
752     int irq = vms->irqmap[uart];
753     const char compat[] = "arm,pl011\0arm,primecell";
754     const char clocknames[] = "uartclk\0apb_pclk";
755     DeviceState *dev = qdev_new(TYPE_PL011);
756     SysBusDevice *s = SYS_BUS_DEVICE(dev);
757 
758     qdev_prop_set_chr(dev, "chardev", chr);
759     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
760     memory_region_add_subregion(mem, base,
761                                 sysbus_mmio_get_region(s, 0));
762     sysbus_connect_irq(s, 0, qdev_get_gpio_in(vms->gic, irq));
763 
764     nodename = g_strdup_printf("/pl011@%" PRIx64, base);
765     qemu_fdt_add_subnode(vms->fdt, nodename);
766     /* Note that we can't use setprop_string because of the embedded NUL */
767     qemu_fdt_setprop(vms->fdt, nodename, "compatible",
768                          compat, sizeof(compat));
769     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
770                                      2, base, 2, size);
771     qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupts",
772                                GIC_FDT_IRQ_TYPE_SPI, irq,
773                                GIC_FDT_IRQ_FLAGS_LEVEL_HI);
774     qemu_fdt_setprop_cells(vms->fdt, nodename, "clocks",
775                                vms->clock_phandle, vms->clock_phandle);
776     qemu_fdt_setprop(vms->fdt, nodename, "clock-names",
777                          clocknames, sizeof(clocknames));
778 
779     if (uart == VIRT_UART) {
780         qemu_fdt_setprop_string(vms->fdt, "/chosen", "stdout-path", nodename);
781     } else {
782         /* Mark as not usable by the normal world */
783         qemu_fdt_setprop_string(vms->fdt, nodename, "status", "disabled");
784         qemu_fdt_setprop_string(vms->fdt, nodename, "secure-status", "okay");
785 
786         qemu_fdt_setprop_string(vms->fdt, "/secure-chosen", "stdout-path",
787                                 nodename);
788     }
789 
790     g_free(nodename);
791 }
792 
793 static void create_rtc(const VirtMachineState *vms)
794 {
795     char *nodename;
796     hwaddr base = vms->memmap[VIRT_RTC].base;
797     hwaddr size = vms->memmap[VIRT_RTC].size;
798     int irq = vms->irqmap[VIRT_RTC];
799     const char compat[] = "arm,pl031\0arm,primecell";
800 
801     sysbus_create_simple("pl031", base, qdev_get_gpio_in(vms->gic, irq));
802 
803     nodename = g_strdup_printf("/pl031@%" PRIx64, base);
804     qemu_fdt_add_subnode(vms->fdt, nodename);
805     qemu_fdt_setprop(vms->fdt, nodename, "compatible", compat, sizeof(compat));
806     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
807                                  2, base, 2, size);
808     qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupts",
809                            GIC_FDT_IRQ_TYPE_SPI, irq,
810                            GIC_FDT_IRQ_FLAGS_LEVEL_HI);
811     qemu_fdt_setprop_cell(vms->fdt, nodename, "clocks", vms->clock_phandle);
812     qemu_fdt_setprop_string(vms->fdt, nodename, "clock-names", "apb_pclk");
813     g_free(nodename);
814 }
815 
816 static DeviceState *gpio_key_dev;
817 static void virt_powerdown_req(Notifier *n, void *opaque)
818 {
819     VirtMachineState *s = container_of(n, VirtMachineState, powerdown_notifier);
820 
821     if (s->acpi_dev) {
822         acpi_send_event(s->acpi_dev, ACPI_POWER_DOWN_STATUS);
823     } else {
824         /* use gpio Pin 3 for power button event */
825         qemu_set_irq(qdev_get_gpio_in(gpio_key_dev, 0), 1);
826     }
827 }
828 
829 static void create_gpio(const VirtMachineState *vms)
830 {
831     char *nodename;
832     DeviceState *pl061_dev;
833     hwaddr base = vms->memmap[VIRT_GPIO].base;
834     hwaddr size = vms->memmap[VIRT_GPIO].size;
835     int irq = vms->irqmap[VIRT_GPIO];
836     const char compat[] = "arm,pl061\0arm,primecell";
837 
838     pl061_dev = sysbus_create_simple("pl061", base,
839                                      qdev_get_gpio_in(vms->gic, irq));
840 
841     uint32_t phandle = qemu_fdt_alloc_phandle(vms->fdt);
842     nodename = g_strdup_printf("/pl061@%" PRIx64, base);
843     qemu_fdt_add_subnode(vms->fdt, nodename);
844     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
845                                  2, base, 2, size);
846     qemu_fdt_setprop(vms->fdt, nodename, "compatible", compat, sizeof(compat));
847     qemu_fdt_setprop_cell(vms->fdt, nodename, "#gpio-cells", 2);
848     qemu_fdt_setprop(vms->fdt, nodename, "gpio-controller", NULL, 0);
849     qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupts",
850                            GIC_FDT_IRQ_TYPE_SPI, irq,
851                            GIC_FDT_IRQ_FLAGS_LEVEL_HI);
852     qemu_fdt_setprop_cell(vms->fdt, nodename, "clocks", vms->clock_phandle);
853     qemu_fdt_setprop_string(vms->fdt, nodename, "clock-names", "apb_pclk");
854     qemu_fdt_setprop_cell(vms->fdt, nodename, "phandle", phandle);
855 
856     gpio_key_dev = sysbus_create_simple("gpio-key", -1,
857                                         qdev_get_gpio_in(pl061_dev, 3));
858     qemu_fdt_add_subnode(vms->fdt, "/gpio-keys");
859     qemu_fdt_setprop_string(vms->fdt, "/gpio-keys", "compatible", "gpio-keys");
860     qemu_fdt_setprop_cell(vms->fdt, "/gpio-keys", "#size-cells", 0);
861     qemu_fdt_setprop_cell(vms->fdt, "/gpio-keys", "#address-cells", 1);
862 
863     qemu_fdt_add_subnode(vms->fdt, "/gpio-keys/poweroff");
864     qemu_fdt_setprop_string(vms->fdt, "/gpio-keys/poweroff",
865                             "label", "GPIO Key Poweroff");
866     qemu_fdt_setprop_cell(vms->fdt, "/gpio-keys/poweroff", "linux,code",
867                           KEY_POWER);
868     qemu_fdt_setprop_cells(vms->fdt, "/gpio-keys/poweroff",
869                            "gpios", phandle, 3, 0);
870     g_free(nodename);
871 }
872 
873 static void create_virtio_devices(const VirtMachineState *vms)
874 {
875     int i;
876     hwaddr size = vms->memmap[VIRT_MMIO].size;
877 
878     /* We create the transports in forwards order. Since qbus_realize()
879      * prepends (not appends) new child buses, the incrementing loop below will
880      * create a list of virtio-mmio buses with decreasing base addresses.
881      *
882      * When a -device option is processed from the command line,
883      * qbus_find_recursive() picks the next free virtio-mmio bus in forwards
884      * order. The upshot is that -device options in increasing command line
885      * order are mapped to virtio-mmio buses with decreasing base addresses.
886      *
887      * When this code was originally written, that arrangement ensured that the
888      * guest Linux kernel would give the lowest "name" (/dev/vda, eth0, etc) to
889      * the first -device on the command line. (The end-to-end order is a
890      * function of this loop, qbus_realize(), qbus_find_recursive(), and the
891      * guest kernel's name-to-address assignment strategy.)
892      *
893      * Meanwhile, the kernel's traversal seems to have been reversed; see eg.
894      * the message, if not necessarily the code, of commit 70161ff336.
895      * Therefore the loop now establishes the inverse of the original intent.
896      *
897      * Unfortunately, we can't counteract the kernel change by reversing the
898      * loop; it would break existing command lines.
899      *
900      * In any case, the kernel makes no guarantee about the stability of
901      * enumeration order of virtio devices (as demonstrated by it changing
902      * between kernel versions). For reliable and stable identification
903      * of disks users must use UUIDs or similar mechanisms.
904      */
905     for (i = 0; i < NUM_VIRTIO_TRANSPORTS; i++) {
906         int irq = vms->irqmap[VIRT_MMIO] + i;
907         hwaddr base = vms->memmap[VIRT_MMIO].base + i * size;
908 
909         sysbus_create_simple("virtio-mmio", base,
910                              qdev_get_gpio_in(vms->gic, irq));
911     }
912 
913     /* We add dtb nodes in reverse order so that they appear in the finished
914      * device tree lowest address first.
915      *
916      * Note that this mapping is independent of the loop above. The previous
917      * loop influences virtio device to virtio transport assignment, whereas
918      * this loop controls how virtio transports are laid out in the dtb.
919      */
920     for (i = NUM_VIRTIO_TRANSPORTS - 1; i >= 0; i--) {
921         char *nodename;
922         int irq = vms->irqmap[VIRT_MMIO] + i;
923         hwaddr base = vms->memmap[VIRT_MMIO].base + i * size;
924 
925         nodename = g_strdup_printf("/virtio_mmio@%" PRIx64, base);
926         qemu_fdt_add_subnode(vms->fdt, nodename);
927         qemu_fdt_setprop_string(vms->fdt, nodename,
928                                 "compatible", "virtio,mmio");
929         qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
930                                      2, base, 2, size);
931         qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupts",
932                                GIC_FDT_IRQ_TYPE_SPI, irq,
933                                GIC_FDT_IRQ_FLAGS_EDGE_LO_HI);
934         qemu_fdt_setprop(vms->fdt, nodename, "dma-coherent", NULL, 0);
935         g_free(nodename);
936     }
937 }
938 
939 #define VIRT_FLASH_SECTOR_SIZE (256 * KiB)
940 
941 static PFlashCFI01 *virt_flash_create1(VirtMachineState *vms,
942                                         const char *name,
943                                         const char *alias_prop_name)
944 {
945     /*
946      * Create a single flash device.  We use the same parameters as
947      * the flash devices on the Versatile Express board.
948      */
949     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI01);
950 
951     qdev_prop_set_uint64(dev, "sector-length", VIRT_FLASH_SECTOR_SIZE);
952     qdev_prop_set_uint8(dev, "width", 4);
953     qdev_prop_set_uint8(dev, "device-width", 2);
954     qdev_prop_set_bit(dev, "big-endian", false);
955     qdev_prop_set_uint16(dev, "id0", 0x89);
956     qdev_prop_set_uint16(dev, "id1", 0x18);
957     qdev_prop_set_uint16(dev, "id2", 0x00);
958     qdev_prop_set_uint16(dev, "id3", 0x00);
959     qdev_prop_set_string(dev, "name", name);
960     object_property_add_child(OBJECT(vms), name, OBJECT(dev));
961     object_property_add_alias(OBJECT(vms), alias_prop_name,
962                               OBJECT(dev), "drive");
963     return PFLASH_CFI01(dev);
964 }
965 
966 static void virt_flash_create(VirtMachineState *vms)
967 {
968     vms->flash[0] = virt_flash_create1(vms, "virt.flash0", "pflash0");
969     vms->flash[1] = virt_flash_create1(vms, "virt.flash1", "pflash1");
970 }
971 
972 static void virt_flash_map1(PFlashCFI01 *flash,
973                             hwaddr base, hwaddr size,
974                             MemoryRegion *sysmem)
975 {
976     DeviceState *dev = DEVICE(flash);
977 
978     assert(QEMU_IS_ALIGNED(size, VIRT_FLASH_SECTOR_SIZE));
979     assert(size / VIRT_FLASH_SECTOR_SIZE <= UINT32_MAX);
980     qdev_prop_set_uint32(dev, "num-blocks", size / VIRT_FLASH_SECTOR_SIZE);
981     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
982 
983     memory_region_add_subregion(sysmem, base,
984                                 sysbus_mmio_get_region(SYS_BUS_DEVICE(dev),
985                                                        0));
986 }
987 
988 static void virt_flash_map(VirtMachineState *vms,
989                            MemoryRegion *sysmem,
990                            MemoryRegion *secure_sysmem)
991 {
992     /*
993      * Map two flash devices to fill the VIRT_FLASH space in the memmap.
994      * sysmem is the system memory space. secure_sysmem is the secure view
995      * of the system, and the first flash device should be made visible only
996      * there. The second flash device is visible to both secure and nonsecure.
997      * If sysmem == secure_sysmem this means there is no separate Secure
998      * address space and both flash devices are generally visible.
999      */
1000     hwaddr flashsize = vms->memmap[VIRT_FLASH].size / 2;
1001     hwaddr flashbase = vms->memmap[VIRT_FLASH].base;
1002 
1003     virt_flash_map1(vms->flash[0], flashbase, flashsize,
1004                     secure_sysmem);
1005     virt_flash_map1(vms->flash[1], flashbase + flashsize, flashsize,
1006                     sysmem);
1007 }
1008 
1009 static void virt_flash_fdt(VirtMachineState *vms,
1010                            MemoryRegion *sysmem,
1011                            MemoryRegion *secure_sysmem)
1012 {
1013     hwaddr flashsize = vms->memmap[VIRT_FLASH].size / 2;
1014     hwaddr flashbase = vms->memmap[VIRT_FLASH].base;
1015     char *nodename;
1016 
1017     if (sysmem == secure_sysmem) {
1018         /* Report both flash devices as a single node in the DT */
1019         nodename = g_strdup_printf("/flash@%" PRIx64, flashbase);
1020         qemu_fdt_add_subnode(vms->fdt, nodename);
1021         qemu_fdt_setprop_string(vms->fdt, nodename, "compatible", "cfi-flash");
1022         qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
1023                                      2, flashbase, 2, flashsize,
1024                                      2, flashbase + flashsize, 2, flashsize);
1025         qemu_fdt_setprop_cell(vms->fdt, nodename, "bank-width", 4);
1026         g_free(nodename);
1027     } else {
1028         /*
1029          * Report the devices as separate nodes so we can mark one as
1030          * only visible to the secure world.
1031          */
1032         nodename = g_strdup_printf("/secflash@%" PRIx64, flashbase);
1033         qemu_fdt_add_subnode(vms->fdt, nodename);
1034         qemu_fdt_setprop_string(vms->fdt, nodename, "compatible", "cfi-flash");
1035         qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
1036                                      2, flashbase, 2, flashsize);
1037         qemu_fdt_setprop_cell(vms->fdt, nodename, "bank-width", 4);
1038         qemu_fdt_setprop_string(vms->fdt, nodename, "status", "disabled");
1039         qemu_fdt_setprop_string(vms->fdt, nodename, "secure-status", "okay");
1040         g_free(nodename);
1041 
1042         nodename = g_strdup_printf("/flash@%" PRIx64, flashbase);
1043         qemu_fdt_add_subnode(vms->fdt, nodename);
1044         qemu_fdt_setprop_string(vms->fdt, nodename, "compatible", "cfi-flash");
1045         qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
1046                                      2, flashbase + flashsize, 2, flashsize);
1047         qemu_fdt_setprop_cell(vms->fdt, nodename, "bank-width", 4);
1048         g_free(nodename);
1049     }
1050 }
1051 
1052 static bool virt_firmware_init(VirtMachineState *vms,
1053                                MemoryRegion *sysmem,
1054                                MemoryRegion *secure_sysmem)
1055 {
1056     int i;
1057     BlockBackend *pflash_blk0;
1058 
1059     /* Map legacy -drive if=pflash to machine properties */
1060     for (i = 0; i < ARRAY_SIZE(vms->flash); i++) {
1061         pflash_cfi01_legacy_drive(vms->flash[i],
1062                                   drive_get(IF_PFLASH, 0, i));
1063     }
1064 
1065     virt_flash_map(vms, sysmem, secure_sysmem);
1066 
1067     pflash_blk0 = pflash_cfi01_get_blk(vms->flash[0]);
1068 
1069     if (bios_name) {
1070         char *fname;
1071         MemoryRegion *mr;
1072         int image_size;
1073 
1074         if (pflash_blk0) {
1075             error_report("The contents of the first flash device may be "
1076                          "specified with -bios or with -drive if=pflash... "
1077                          "but you cannot use both options at once");
1078             exit(1);
1079         }
1080 
1081         /* Fall back to -bios */
1082 
1083         fname = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
1084         if (!fname) {
1085             error_report("Could not find ROM image '%s'", bios_name);
1086             exit(1);
1087         }
1088         mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(vms->flash[0]), 0);
1089         image_size = load_image_mr(fname, mr);
1090         g_free(fname);
1091         if (image_size < 0) {
1092             error_report("Could not load ROM image '%s'", bios_name);
1093             exit(1);
1094         }
1095     }
1096 
1097     return pflash_blk0 || bios_name;
1098 }
1099 
1100 static FWCfgState *create_fw_cfg(const VirtMachineState *vms, AddressSpace *as)
1101 {
1102     MachineState *ms = MACHINE(vms);
1103     hwaddr base = vms->memmap[VIRT_FW_CFG].base;
1104     hwaddr size = vms->memmap[VIRT_FW_CFG].size;
1105     FWCfgState *fw_cfg;
1106     char *nodename;
1107 
1108     fw_cfg = fw_cfg_init_mem_wide(base + 8, base, 8, base + 16, as);
1109     fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, (uint16_t)ms->smp.cpus);
1110 
1111     nodename = g_strdup_printf("/fw-cfg@%" PRIx64, base);
1112     qemu_fdt_add_subnode(vms->fdt, nodename);
1113     qemu_fdt_setprop_string(vms->fdt, nodename,
1114                             "compatible", "qemu,fw-cfg-mmio");
1115     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
1116                                  2, base, 2, size);
1117     qemu_fdt_setprop(vms->fdt, nodename, "dma-coherent", NULL, 0);
1118     g_free(nodename);
1119     return fw_cfg;
1120 }
1121 
1122 static void create_pcie_irq_map(const VirtMachineState *vms,
1123                                 uint32_t gic_phandle,
1124                                 int first_irq, const char *nodename)
1125 {
1126     int devfn, pin;
1127     uint32_t full_irq_map[4 * 4 * 10] = { 0 };
1128     uint32_t *irq_map = full_irq_map;
1129 
1130     for (devfn = 0; devfn <= 0x18; devfn += 0x8) {
1131         for (pin = 0; pin < 4; pin++) {
1132             int irq_type = GIC_FDT_IRQ_TYPE_SPI;
1133             int irq_nr = first_irq + ((pin + PCI_SLOT(devfn)) % PCI_NUM_PINS);
1134             int irq_level = GIC_FDT_IRQ_FLAGS_LEVEL_HI;
1135             int i;
1136 
1137             uint32_t map[] = {
1138                 devfn << 8, 0, 0,                           /* devfn */
1139                 pin + 1,                                    /* PCI pin */
1140                 gic_phandle, 0, 0, irq_type, irq_nr, irq_level }; /* GIC irq */
1141 
1142             /* Convert map to big endian */
1143             for (i = 0; i < 10; i++) {
1144                 irq_map[i] = cpu_to_be32(map[i]);
1145             }
1146             irq_map += 10;
1147         }
1148     }
1149 
1150     qemu_fdt_setprop(vms->fdt, nodename, "interrupt-map",
1151                      full_irq_map, sizeof(full_irq_map));
1152 
1153     qemu_fdt_setprop_cells(vms->fdt, nodename, "interrupt-map-mask",
1154                            0x1800, 0, 0, /* devfn (PCI_SLOT(3)) */
1155                            0x7           /* PCI irq */);
1156 }
1157 
1158 static void create_smmu(const VirtMachineState *vms,
1159                         PCIBus *bus)
1160 {
1161     char *node;
1162     const char compat[] = "arm,smmu-v3";
1163     int irq =  vms->irqmap[VIRT_SMMU];
1164     int i;
1165     hwaddr base = vms->memmap[VIRT_SMMU].base;
1166     hwaddr size = vms->memmap[VIRT_SMMU].size;
1167     const char irq_names[] = "eventq\0priq\0cmdq-sync\0gerror";
1168     DeviceState *dev;
1169 
1170     if (vms->iommu != VIRT_IOMMU_SMMUV3 || !vms->iommu_phandle) {
1171         return;
1172     }
1173 
1174     dev = qdev_new("arm-smmuv3");
1175 
1176     object_property_set_link(OBJECT(dev), OBJECT(bus), "primary-bus",
1177                              &error_abort);
1178     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1179     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);
1180     for (i = 0; i < NUM_SMMU_IRQS; i++) {
1181         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
1182                            qdev_get_gpio_in(vms->gic, irq + i));
1183     }
1184 
1185     node = g_strdup_printf("/smmuv3@%" PRIx64, base);
1186     qemu_fdt_add_subnode(vms->fdt, node);
1187     qemu_fdt_setprop(vms->fdt, node, "compatible", compat, sizeof(compat));
1188     qemu_fdt_setprop_sized_cells(vms->fdt, node, "reg", 2, base, 2, size);
1189 
1190     qemu_fdt_setprop_cells(vms->fdt, node, "interrupts",
1191             GIC_FDT_IRQ_TYPE_SPI, irq    , GIC_FDT_IRQ_FLAGS_EDGE_LO_HI,
1192             GIC_FDT_IRQ_TYPE_SPI, irq + 1, GIC_FDT_IRQ_FLAGS_EDGE_LO_HI,
1193             GIC_FDT_IRQ_TYPE_SPI, irq + 2, GIC_FDT_IRQ_FLAGS_EDGE_LO_HI,
1194             GIC_FDT_IRQ_TYPE_SPI, irq + 3, GIC_FDT_IRQ_FLAGS_EDGE_LO_HI);
1195 
1196     qemu_fdt_setprop(vms->fdt, node, "interrupt-names", irq_names,
1197                      sizeof(irq_names));
1198 
1199     qemu_fdt_setprop_cell(vms->fdt, node, "clocks", vms->clock_phandle);
1200     qemu_fdt_setprop_string(vms->fdt, node, "clock-names", "apb_pclk");
1201     qemu_fdt_setprop(vms->fdt, node, "dma-coherent", NULL, 0);
1202 
1203     qemu_fdt_setprop_cell(vms->fdt, node, "#iommu-cells", 1);
1204 
1205     qemu_fdt_setprop_cell(vms->fdt, node, "phandle", vms->iommu_phandle);
1206     g_free(node);
1207 }
1208 
1209 static void create_virtio_iommu_dt_bindings(VirtMachineState *vms)
1210 {
1211     const char compat[] = "virtio,pci-iommu";
1212     uint16_t bdf = vms->virtio_iommu_bdf;
1213     char *node;
1214 
1215     vms->iommu_phandle = qemu_fdt_alloc_phandle(vms->fdt);
1216 
1217     node = g_strdup_printf("%s/virtio_iommu@%d", vms->pciehb_nodename, bdf);
1218     qemu_fdt_add_subnode(vms->fdt, node);
1219     qemu_fdt_setprop(vms->fdt, node, "compatible", compat, sizeof(compat));
1220     qemu_fdt_setprop_sized_cells(vms->fdt, node, "reg",
1221                                  1, bdf << 8, 1, 0, 1, 0,
1222                                  1, 0, 1, 0);
1223 
1224     qemu_fdt_setprop_cell(vms->fdt, node, "#iommu-cells", 1);
1225     qemu_fdt_setprop_cell(vms->fdt, node, "phandle", vms->iommu_phandle);
1226     g_free(node);
1227 
1228     qemu_fdt_setprop_cells(vms->fdt, vms->pciehb_nodename, "iommu-map",
1229                            0x0, vms->iommu_phandle, 0x0, bdf,
1230                            bdf + 1, vms->iommu_phandle, bdf + 1, 0xffff - bdf);
1231 }
1232 
1233 static void create_pcie(VirtMachineState *vms)
1234 {
1235     hwaddr base_mmio = vms->memmap[VIRT_PCIE_MMIO].base;
1236     hwaddr size_mmio = vms->memmap[VIRT_PCIE_MMIO].size;
1237     hwaddr base_mmio_high = vms->memmap[VIRT_HIGH_PCIE_MMIO].base;
1238     hwaddr size_mmio_high = vms->memmap[VIRT_HIGH_PCIE_MMIO].size;
1239     hwaddr base_pio = vms->memmap[VIRT_PCIE_PIO].base;
1240     hwaddr size_pio = vms->memmap[VIRT_PCIE_PIO].size;
1241     hwaddr base_ecam, size_ecam;
1242     hwaddr base = base_mmio;
1243     int nr_pcie_buses;
1244     int irq = vms->irqmap[VIRT_PCIE];
1245     MemoryRegion *mmio_alias;
1246     MemoryRegion *mmio_reg;
1247     MemoryRegion *ecam_alias;
1248     MemoryRegion *ecam_reg;
1249     DeviceState *dev;
1250     char *nodename;
1251     int i, ecam_id;
1252     PCIHostState *pci;
1253 
1254     dev = qdev_new(TYPE_GPEX_HOST);
1255     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1256 
1257     ecam_id = VIRT_ECAM_ID(vms->highmem_ecam);
1258     base_ecam = vms->memmap[ecam_id].base;
1259     size_ecam = vms->memmap[ecam_id].size;
1260     nr_pcie_buses = size_ecam / PCIE_MMCFG_SIZE_MIN;
1261     /* Map only the first size_ecam bytes of ECAM space */
1262     ecam_alias = g_new0(MemoryRegion, 1);
1263     ecam_reg = sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 0);
1264     memory_region_init_alias(ecam_alias, OBJECT(dev), "pcie-ecam",
1265                              ecam_reg, 0, size_ecam);
1266     memory_region_add_subregion(get_system_memory(), base_ecam, ecam_alias);
1267 
1268     /* Map the MMIO window into system address space so as to expose
1269      * the section of PCI MMIO space which starts at the same base address
1270      * (ie 1:1 mapping for that part of PCI MMIO space visible through
1271      * the window).
1272      */
1273     mmio_alias = g_new0(MemoryRegion, 1);
1274     mmio_reg = sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 1);
1275     memory_region_init_alias(mmio_alias, OBJECT(dev), "pcie-mmio",
1276                              mmio_reg, base_mmio, size_mmio);
1277     memory_region_add_subregion(get_system_memory(), base_mmio, mmio_alias);
1278 
1279     if (vms->highmem) {
1280         /* Map high MMIO space */
1281         MemoryRegion *high_mmio_alias = g_new0(MemoryRegion, 1);
1282 
1283         memory_region_init_alias(high_mmio_alias, OBJECT(dev), "pcie-mmio-high",
1284                                  mmio_reg, base_mmio_high, size_mmio_high);
1285         memory_region_add_subregion(get_system_memory(), base_mmio_high,
1286                                     high_mmio_alias);
1287     }
1288 
1289     /* Map IO port space */
1290     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
1291 
1292     for (i = 0; i < GPEX_NUM_IRQS; i++) {
1293         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
1294                            qdev_get_gpio_in(vms->gic, irq + i));
1295         gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
1296     }
1297 
1298     pci = PCI_HOST_BRIDGE(dev);
1299     if (pci->bus) {
1300         for (i = 0; i < nb_nics; i++) {
1301             NICInfo *nd = &nd_table[i];
1302 
1303             if (!nd->model) {
1304                 nd->model = g_strdup("virtio");
1305             }
1306 
1307             pci_nic_init_nofail(nd, pci->bus, nd->model, NULL);
1308         }
1309     }
1310 
1311     nodename = vms->pciehb_nodename = g_strdup_printf("/pcie@%" PRIx64, base);
1312     qemu_fdt_add_subnode(vms->fdt, nodename);
1313     qemu_fdt_setprop_string(vms->fdt, nodename,
1314                             "compatible", "pci-host-ecam-generic");
1315     qemu_fdt_setprop_string(vms->fdt, nodename, "device_type", "pci");
1316     qemu_fdt_setprop_cell(vms->fdt, nodename, "#address-cells", 3);
1317     qemu_fdt_setprop_cell(vms->fdt, nodename, "#size-cells", 2);
1318     qemu_fdt_setprop_cell(vms->fdt, nodename, "linux,pci-domain", 0);
1319     qemu_fdt_setprop_cells(vms->fdt, nodename, "bus-range", 0,
1320                            nr_pcie_buses - 1);
1321     qemu_fdt_setprop(vms->fdt, nodename, "dma-coherent", NULL, 0);
1322 
1323     if (vms->msi_phandle) {
1324         qemu_fdt_setprop_cells(vms->fdt, nodename, "msi-parent",
1325                                vms->msi_phandle);
1326     }
1327 
1328     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg",
1329                                  2, base_ecam, 2, size_ecam);
1330 
1331     if (vms->highmem) {
1332         qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "ranges",
1333                                      1, FDT_PCI_RANGE_IOPORT, 2, 0,
1334                                      2, base_pio, 2, size_pio,
1335                                      1, FDT_PCI_RANGE_MMIO, 2, base_mmio,
1336                                      2, base_mmio, 2, size_mmio,
1337                                      1, FDT_PCI_RANGE_MMIO_64BIT,
1338                                      2, base_mmio_high,
1339                                      2, base_mmio_high, 2, size_mmio_high);
1340     } else {
1341         qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "ranges",
1342                                      1, FDT_PCI_RANGE_IOPORT, 2, 0,
1343                                      2, base_pio, 2, size_pio,
1344                                      1, FDT_PCI_RANGE_MMIO, 2, base_mmio,
1345                                      2, base_mmio, 2, size_mmio);
1346     }
1347 
1348     qemu_fdt_setprop_cell(vms->fdt, nodename, "#interrupt-cells", 1);
1349     create_pcie_irq_map(vms, vms->gic_phandle, irq, nodename);
1350 
1351     if (vms->iommu) {
1352         vms->iommu_phandle = qemu_fdt_alloc_phandle(vms->fdt);
1353 
1354         switch (vms->iommu) {
1355         case VIRT_IOMMU_SMMUV3:
1356             create_smmu(vms, pci->bus);
1357             qemu_fdt_setprop_cells(vms->fdt, nodename, "iommu-map",
1358                                    0x0, vms->iommu_phandle, 0x0, 0x10000);
1359             break;
1360         default:
1361             g_assert_not_reached();
1362         }
1363     }
1364 }
1365 
1366 static void create_platform_bus(VirtMachineState *vms)
1367 {
1368     DeviceState *dev;
1369     SysBusDevice *s;
1370     int i;
1371     MemoryRegion *sysmem = get_system_memory();
1372 
1373     dev = qdev_new(TYPE_PLATFORM_BUS_DEVICE);
1374     dev->id = TYPE_PLATFORM_BUS_DEVICE;
1375     qdev_prop_set_uint32(dev, "num_irqs", PLATFORM_BUS_NUM_IRQS);
1376     qdev_prop_set_uint32(dev, "mmio_size", vms->memmap[VIRT_PLATFORM_BUS].size);
1377     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1378     vms->platform_bus_dev = dev;
1379 
1380     s = SYS_BUS_DEVICE(dev);
1381     for (i = 0; i < PLATFORM_BUS_NUM_IRQS; i++) {
1382         int irq = vms->irqmap[VIRT_PLATFORM_BUS] + i;
1383         sysbus_connect_irq(s, i, qdev_get_gpio_in(vms->gic, irq));
1384     }
1385 
1386     memory_region_add_subregion(sysmem,
1387                                 vms->memmap[VIRT_PLATFORM_BUS].base,
1388                                 sysbus_mmio_get_region(s, 0));
1389 }
1390 
1391 static void create_tag_ram(MemoryRegion *tag_sysmem,
1392                            hwaddr base, hwaddr size,
1393                            const char *name)
1394 {
1395     MemoryRegion *tagram = g_new(MemoryRegion, 1);
1396 
1397     memory_region_init_ram(tagram, NULL, name, size / 32, &error_fatal);
1398     memory_region_add_subregion(tag_sysmem, base / 32, tagram);
1399 }
1400 
1401 static void create_secure_ram(VirtMachineState *vms,
1402                               MemoryRegion *secure_sysmem,
1403                               MemoryRegion *secure_tag_sysmem)
1404 {
1405     MemoryRegion *secram = g_new(MemoryRegion, 1);
1406     char *nodename;
1407     hwaddr base = vms->memmap[VIRT_SECURE_MEM].base;
1408     hwaddr size = vms->memmap[VIRT_SECURE_MEM].size;
1409 
1410     memory_region_init_ram(secram, NULL, "virt.secure-ram", size,
1411                            &error_fatal);
1412     memory_region_add_subregion(secure_sysmem, base, secram);
1413 
1414     nodename = g_strdup_printf("/secram@%" PRIx64, base);
1415     qemu_fdt_add_subnode(vms->fdt, nodename);
1416     qemu_fdt_setprop_string(vms->fdt, nodename, "device_type", "memory");
1417     qemu_fdt_setprop_sized_cells(vms->fdt, nodename, "reg", 2, base, 2, size);
1418     qemu_fdt_setprop_string(vms->fdt, nodename, "status", "disabled");
1419     qemu_fdt_setprop_string(vms->fdt, nodename, "secure-status", "okay");
1420 
1421     if (secure_tag_sysmem) {
1422         create_tag_ram(secure_tag_sysmem, base, size, "mach-virt.secure-tag");
1423     }
1424 
1425     g_free(nodename);
1426 }
1427 
1428 static void *machvirt_dtb(const struct arm_boot_info *binfo, int *fdt_size)
1429 {
1430     const VirtMachineState *board = container_of(binfo, VirtMachineState,
1431                                                  bootinfo);
1432 
1433     *fdt_size = board->fdt_size;
1434     return board->fdt;
1435 }
1436 
1437 static void virt_build_smbios(VirtMachineState *vms)
1438 {
1439     MachineClass *mc = MACHINE_GET_CLASS(vms);
1440     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
1441     uint8_t *smbios_tables, *smbios_anchor;
1442     size_t smbios_tables_len, smbios_anchor_len;
1443     const char *product = "QEMU Virtual Machine";
1444 
1445     if (kvm_enabled()) {
1446         product = "KVM Virtual Machine";
1447     }
1448 
1449     smbios_set_defaults("QEMU", product,
1450                         vmc->smbios_old_sys_ver ? "1.0" : mc->name, false,
1451                         true, SMBIOS_ENTRY_POINT_30);
1452 
1453     smbios_get_tables(MACHINE(vms), NULL, 0, &smbios_tables, &smbios_tables_len,
1454                       &smbios_anchor, &smbios_anchor_len);
1455 
1456     if (smbios_anchor) {
1457         fw_cfg_add_file(vms->fw_cfg, "etc/smbios/smbios-tables",
1458                         smbios_tables, smbios_tables_len);
1459         fw_cfg_add_file(vms->fw_cfg, "etc/smbios/smbios-anchor",
1460                         smbios_anchor, smbios_anchor_len);
1461     }
1462 }
1463 
1464 static
1465 void virt_machine_done(Notifier *notifier, void *data)
1466 {
1467     VirtMachineState *vms = container_of(notifier, VirtMachineState,
1468                                          machine_done);
1469     MachineState *ms = MACHINE(vms);
1470     ARMCPU *cpu = ARM_CPU(first_cpu);
1471     struct arm_boot_info *info = &vms->bootinfo;
1472     AddressSpace *as = arm_boot_address_space(cpu, info);
1473 
1474     /*
1475      * If the user provided a dtb, we assume the dynamic sysbus nodes
1476      * already are integrated there. This corresponds to a use case where
1477      * the dynamic sysbus nodes are complex and their generation is not yet
1478      * supported. In that case the user can take charge of the guest dt
1479      * while qemu takes charge of the qom stuff.
1480      */
1481     if (info->dtb_filename == NULL) {
1482         platform_bus_add_all_fdt_nodes(vms->fdt, "/intc",
1483                                        vms->memmap[VIRT_PLATFORM_BUS].base,
1484                                        vms->memmap[VIRT_PLATFORM_BUS].size,
1485                                        vms->irqmap[VIRT_PLATFORM_BUS]);
1486     }
1487     if (arm_load_dtb(info->dtb_start, info, info->dtb_limit, as, ms) < 0) {
1488         exit(1);
1489     }
1490 
1491     virt_acpi_setup(vms);
1492     virt_build_smbios(vms);
1493 }
1494 
1495 static uint64_t virt_cpu_mp_affinity(VirtMachineState *vms, int idx)
1496 {
1497     uint8_t clustersz = ARM_DEFAULT_CPUS_PER_CLUSTER;
1498     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
1499 
1500     if (!vmc->disallow_affinity_adjustment) {
1501         /* Adjust MPIDR like 64-bit KVM hosts, which incorporate the
1502          * GIC's target-list limitations. 32-bit KVM hosts currently
1503          * always create clusters of 4 CPUs, but that is expected to
1504          * change when they gain support for gicv3. When KVM is enabled
1505          * it will override the changes we make here, therefore our
1506          * purposes are to make TCG consistent (with 64-bit KVM hosts)
1507          * and to improve SGI efficiency.
1508          */
1509         if (vms->gic_version == VIRT_GIC_VERSION_3) {
1510             clustersz = GICV3_TARGETLIST_BITS;
1511         } else {
1512             clustersz = GIC_TARGETLIST_BITS;
1513         }
1514     }
1515     return arm_cpu_mp_affinity(idx, clustersz);
1516 }
1517 
1518 static void virt_set_memmap(VirtMachineState *vms)
1519 {
1520     MachineState *ms = MACHINE(vms);
1521     hwaddr base, device_memory_base, device_memory_size;
1522     int i;
1523 
1524     vms->memmap = extended_memmap;
1525 
1526     for (i = 0; i < ARRAY_SIZE(base_memmap); i++) {
1527         vms->memmap[i] = base_memmap[i];
1528     }
1529 
1530     if (ms->ram_slots > ACPI_MAX_RAM_SLOTS) {
1531         error_report("unsupported number of memory slots: %"PRIu64,
1532                      ms->ram_slots);
1533         exit(EXIT_FAILURE);
1534     }
1535 
1536     /*
1537      * We compute the base of the high IO region depending on the
1538      * amount of initial and device memory. The device memory start/size
1539      * is aligned on 1GiB. We never put the high IO region below 256GiB
1540      * so that if maxram_size is < 255GiB we keep the legacy memory map.
1541      * The device region size assumes 1GiB page max alignment per slot.
1542      */
1543     device_memory_base =
1544         ROUND_UP(vms->memmap[VIRT_MEM].base + ms->ram_size, GiB);
1545     device_memory_size = ms->maxram_size - ms->ram_size + ms->ram_slots * GiB;
1546 
1547     /* Base address of the high IO region */
1548     base = device_memory_base + ROUND_UP(device_memory_size, GiB);
1549     if (base < device_memory_base) {
1550         error_report("maxmem/slots too huge");
1551         exit(EXIT_FAILURE);
1552     }
1553     if (base < vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES) {
1554         base = vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES;
1555     }
1556 
1557     for (i = VIRT_LOWMEMMAP_LAST; i < ARRAY_SIZE(extended_memmap); i++) {
1558         hwaddr size = extended_memmap[i].size;
1559 
1560         base = ROUND_UP(base, size);
1561         vms->memmap[i].base = base;
1562         vms->memmap[i].size = size;
1563         base += size;
1564     }
1565     vms->highest_gpa = base - 1;
1566     if (device_memory_size > 0) {
1567         ms->device_memory = g_malloc0(sizeof(*ms->device_memory));
1568         ms->device_memory->base = device_memory_base;
1569         memory_region_init(&ms->device_memory->mr, OBJECT(vms),
1570                            "device-memory", device_memory_size);
1571     }
1572 }
1573 
1574 /*
1575  * finalize_gic_version - Determines the final gic_version
1576  * according to the gic-version property
1577  *
1578  * Default GIC type is v2
1579  */
1580 static void finalize_gic_version(VirtMachineState *vms)
1581 {
1582     unsigned int max_cpus = MACHINE(vms)->smp.max_cpus;
1583 
1584     if (kvm_enabled()) {
1585         int probe_bitmap;
1586 
1587         if (!kvm_irqchip_in_kernel()) {
1588             switch (vms->gic_version) {
1589             case VIRT_GIC_VERSION_HOST:
1590                 warn_report(
1591                     "gic-version=host not relevant with kernel-irqchip=off "
1592                      "as only userspace GICv2 is supported. Using v2 ...");
1593                 return;
1594             case VIRT_GIC_VERSION_MAX:
1595             case VIRT_GIC_VERSION_NOSEL:
1596                 vms->gic_version = VIRT_GIC_VERSION_2;
1597                 return;
1598             case VIRT_GIC_VERSION_2:
1599                 return;
1600             case VIRT_GIC_VERSION_3:
1601                 error_report(
1602                     "gic-version=3 is not supported with kernel-irqchip=off");
1603                 exit(1);
1604             }
1605         }
1606 
1607         probe_bitmap = kvm_arm_vgic_probe();
1608         if (!probe_bitmap) {
1609             error_report("Unable to determine GIC version supported by host");
1610             exit(1);
1611         }
1612 
1613         switch (vms->gic_version) {
1614         case VIRT_GIC_VERSION_HOST:
1615         case VIRT_GIC_VERSION_MAX:
1616             if (probe_bitmap & KVM_ARM_VGIC_V3) {
1617                 vms->gic_version = VIRT_GIC_VERSION_3;
1618             } else {
1619                 vms->gic_version = VIRT_GIC_VERSION_2;
1620             }
1621             return;
1622         case VIRT_GIC_VERSION_NOSEL:
1623             if ((probe_bitmap & KVM_ARM_VGIC_V2) && max_cpus <= GIC_NCPU) {
1624                 vms->gic_version = VIRT_GIC_VERSION_2;
1625             } else if (probe_bitmap & KVM_ARM_VGIC_V3) {
1626                 /*
1627                  * in case the host does not support v2 in-kernel emulation or
1628                  * the end-user requested more than 8 VCPUs we now default
1629                  * to v3. In any case defaulting to v2 would be broken.
1630                  */
1631                 vms->gic_version = VIRT_GIC_VERSION_3;
1632             } else if (max_cpus > GIC_NCPU) {
1633                 error_report("host only supports in-kernel GICv2 emulation "
1634                              "but more than 8 vcpus are requested");
1635                 exit(1);
1636             }
1637             break;
1638         case VIRT_GIC_VERSION_2:
1639         case VIRT_GIC_VERSION_3:
1640             break;
1641         }
1642 
1643         /* Check chosen version is effectively supported by the host */
1644         if (vms->gic_version == VIRT_GIC_VERSION_2 &&
1645             !(probe_bitmap & KVM_ARM_VGIC_V2)) {
1646             error_report("host does not support in-kernel GICv2 emulation");
1647             exit(1);
1648         } else if (vms->gic_version == VIRT_GIC_VERSION_3 &&
1649                    !(probe_bitmap & KVM_ARM_VGIC_V3)) {
1650             error_report("host does not support in-kernel GICv3 emulation");
1651             exit(1);
1652         }
1653         return;
1654     }
1655 
1656     /* TCG mode */
1657     switch (vms->gic_version) {
1658     case VIRT_GIC_VERSION_NOSEL:
1659         vms->gic_version = VIRT_GIC_VERSION_2;
1660         break;
1661     case VIRT_GIC_VERSION_MAX:
1662         vms->gic_version = VIRT_GIC_VERSION_3;
1663         break;
1664     case VIRT_GIC_VERSION_HOST:
1665         error_report("gic-version=host requires KVM");
1666         exit(1);
1667     case VIRT_GIC_VERSION_2:
1668     case VIRT_GIC_VERSION_3:
1669         break;
1670     }
1671 }
1672 
1673 static void machvirt_init(MachineState *machine)
1674 {
1675     VirtMachineState *vms = VIRT_MACHINE(machine);
1676     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(machine);
1677     MachineClass *mc = MACHINE_GET_CLASS(machine);
1678     const CPUArchIdList *possible_cpus;
1679     MemoryRegion *sysmem = get_system_memory();
1680     MemoryRegion *secure_sysmem = NULL;
1681     MemoryRegion *tag_sysmem = NULL;
1682     MemoryRegion *secure_tag_sysmem = NULL;
1683     int n, virt_max_cpus;
1684     bool firmware_loaded;
1685     bool aarch64 = true;
1686     bool has_ged = !vmc->no_ged;
1687     unsigned int smp_cpus = machine->smp.cpus;
1688     unsigned int max_cpus = machine->smp.max_cpus;
1689 
1690     /*
1691      * In accelerated mode, the memory map is computed earlier in kvm_type()
1692      * to create a VM with the right number of IPA bits.
1693      */
1694     if (!vms->memmap) {
1695         virt_set_memmap(vms);
1696     }
1697 
1698     /* We can probe only here because during property set
1699      * KVM is not available yet
1700      */
1701     finalize_gic_version(vms);
1702 
1703     if (!cpu_type_valid(machine->cpu_type)) {
1704         error_report("mach-virt: CPU type %s not supported", machine->cpu_type);
1705         exit(1);
1706     }
1707 
1708     if (vms->secure) {
1709         if (kvm_enabled()) {
1710             error_report("mach-virt: KVM does not support Security extensions");
1711             exit(1);
1712         }
1713 
1714         /*
1715          * The Secure view of the world is the same as the NonSecure,
1716          * but with a few extra devices. Create it as a container region
1717          * containing the system memory at low priority; any secure-only
1718          * devices go in at higher priority and take precedence.
1719          */
1720         secure_sysmem = g_new(MemoryRegion, 1);
1721         memory_region_init(secure_sysmem, OBJECT(machine), "secure-memory",
1722                            UINT64_MAX);
1723         memory_region_add_subregion_overlap(secure_sysmem, 0, sysmem, -1);
1724     }
1725 
1726     firmware_loaded = virt_firmware_init(vms, sysmem,
1727                                          secure_sysmem ?: sysmem);
1728 
1729     /* If we have an EL3 boot ROM then the assumption is that it will
1730      * implement PSCI itself, so disable QEMU's internal implementation
1731      * so it doesn't get in the way. Instead of starting secondary
1732      * CPUs in PSCI powerdown state we will start them all running and
1733      * let the boot ROM sort them out.
1734      * The usual case is that we do use QEMU's PSCI implementation;
1735      * if the guest has EL2 then we will use SMC as the conduit,
1736      * and otherwise we will use HVC (for backwards compatibility and
1737      * because if we're using KVM then we must use HVC).
1738      */
1739     if (vms->secure && firmware_loaded) {
1740         vms->psci_conduit = QEMU_PSCI_CONDUIT_DISABLED;
1741     } else if (vms->virt) {
1742         vms->psci_conduit = QEMU_PSCI_CONDUIT_SMC;
1743     } else {
1744         vms->psci_conduit = QEMU_PSCI_CONDUIT_HVC;
1745     }
1746 
1747     /* The maximum number of CPUs depends on the GIC version, or on how
1748      * many redistributors we can fit into the memory map.
1749      */
1750     if (vms->gic_version == VIRT_GIC_VERSION_3) {
1751         virt_max_cpus =
1752             vms->memmap[VIRT_GIC_REDIST].size / GICV3_REDIST_SIZE;
1753         virt_max_cpus +=
1754             vms->memmap[VIRT_HIGH_GIC_REDIST2].size / GICV3_REDIST_SIZE;
1755     } else {
1756         virt_max_cpus = GIC_NCPU;
1757     }
1758 
1759     if (max_cpus > virt_max_cpus) {
1760         error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "
1761                      "supported by machine 'mach-virt' (%d)",
1762                      max_cpus, virt_max_cpus);
1763         exit(1);
1764     }
1765 
1766     vms->smp_cpus = smp_cpus;
1767 
1768     if (vms->virt && kvm_enabled()) {
1769         error_report("mach-virt: KVM does not support providing "
1770                      "Virtualization extensions to the guest CPU");
1771         exit(1);
1772     }
1773 
1774     create_fdt(vms);
1775 
1776     possible_cpus = mc->possible_cpu_arch_ids(machine);
1777     for (n = 0; n < possible_cpus->len; n++) {
1778         Object *cpuobj;
1779         CPUState *cs;
1780 
1781         if (n >= smp_cpus) {
1782             break;
1783         }
1784 
1785         cpuobj = object_new(possible_cpus->cpus[n].type);
1786         object_property_set_int(cpuobj, possible_cpus->cpus[n].arch_id,
1787                                 "mp-affinity", NULL);
1788 
1789         cs = CPU(cpuobj);
1790         cs->cpu_index = n;
1791 
1792         numa_cpu_pre_plug(&possible_cpus->cpus[cs->cpu_index], DEVICE(cpuobj),
1793                           &error_fatal);
1794 
1795         aarch64 &= object_property_get_bool(cpuobj, "aarch64", NULL);
1796 
1797         if (!vms->secure) {
1798             object_property_set_bool(cpuobj, false, "has_el3", NULL);
1799         }
1800 
1801         if (!vms->virt && object_property_find(cpuobj, "has_el2", NULL)) {
1802             object_property_set_bool(cpuobj, false, "has_el2", NULL);
1803         }
1804 
1805         if (vms->psci_conduit != QEMU_PSCI_CONDUIT_DISABLED) {
1806             object_property_set_int(cpuobj, vms->psci_conduit,
1807                                     "psci-conduit", NULL);
1808 
1809             /* Secondary CPUs start in PSCI powered-down state */
1810             if (n > 0) {
1811                 object_property_set_bool(cpuobj, true,
1812                                          "start-powered-off", NULL);
1813             }
1814         }
1815 
1816         if (vmc->kvm_no_adjvtime &&
1817             object_property_find(cpuobj, "kvm-no-adjvtime", NULL)) {
1818             object_property_set_bool(cpuobj, true, "kvm-no-adjvtime", NULL);
1819         }
1820 
1821         if (vmc->no_pmu && object_property_find(cpuobj, "pmu", NULL)) {
1822             object_property_set_bool(cpuobj, false, "pmu", NULL);
1823         }
1824 
1825         if (object_property_find(cpuobj, "reset-cbar", NULL)) {
1826             object_property_set_int(cpuobj, vms->memmap[VIRT_CPUPERIPHS].base,
1827                                     "reset-cbar", &error_abort);
1828         }
1829 
1830         object_property_set_link(cpuobj, OBJECT(sysmem), "memory",
1831                                  &error_abort);
1832         if (vms->secure) {
1833             object_property_set_link(cpuobj, OBJECT(secure_sysmem),
1834                                      "secure-memory", &error_abort);
1835         }
1836 
1837         /*
1838          * The cpu adds the property if and only if MemTag is supported.
1839          * If it is, we must allocate the ram to back that up.
1840          */
1841         if (object_property_find(cpuobj, "tag-memory", NULL)) {
1842             if (!tag_sysmem) {
1843                 tag_sysmem = g_new(MemoryRegion, 1);
1844                 memory_region_init(tag_sysmem, OBJECT(machine),
1845                                    "tag-memory", UINT64_MAX / 32);
1846 
1847                 if (vms->secure) {
1848                     secure_tag_sysmem = g_new(MemoryRegion, 1);
1849                     memory_region_init(secure_tag_sysmem, OBJECT(machine),
1850                                        "secure-tag-memory", UINT64_MAX / 32);
1851 
1852                     /* As with ram, secure-tag takes precedence over tag.  */
1853                     memory_region_add_subregion_overlap(secure_tag_sysmem, 0,
1854                                                         tag_sysmem, -1);
1855                 }
1856             }
1857 
1858             object_property_set_link(cpuobj, OBJECT(tag_sysmem),
1859                                      "tag-memory", &error_abort);
1860             if (vms->secure) {
1861                 object_property_set_link(cpuobj, OBJECT(secure_tag_sysmem),
1862                                          "secure-tag-memory", &error_abort);
1863             }
1864         }
1865 
1866         qdev_realize(DEVICE(cpuobj), NULL, &error_fatal);
1867         object_unref(cpuobj);
1868     }
1869     fdt_add_timer_nodes(vms);
1870     fdt_add_cpu_nodes(vms);
1871 
1872    if (!kvm_enabled()) {
1873         ARMCPU *cpu = ARM_CPU(first_cpu);
1874         bool aarch64 = object_property_get_bool(OBJECT(cpu), "aarch64", NULL);
1875 
1876         if (aarch64 && vms->highmem) {
1877             int requested_pa_size, pamax = arm_pamax(cpu);
1878 
1879             requested_pa_size = 64 - clz64(vms->highest_gpa);
1880             if (pamax < requested_pa_size) {
1881                 error_report("VCPU supports less PA bits (%d) than requested "
1882                             "by the memory map (%d)", pamax, requested_pa_size);
1883                 exit(1);
1884             }
1885         }
1886     }
1887 
1888     memory_region_add_subregion(sysmem, vms->memmap[VIRT_MEM].base,
1889                                 machine->ram);
1890     if (machine->device_memory) {
1891         memory_region_add_subregion(sysmem, machine->device_memory->base,
1892                                     &machine->device_memory->mr);
1893     }
1894 
1895     virt_flash_fdt(vms, sysmem, secure_sysmem ?: sysmem);
1896 
1897     create_gic(vms);
1898 
1899     fdt_add_pmu_nodes(vms);
1900 
1901     create_uart(vms, VIRT_UART, sysmem, serial_hd(0));
1902 
1903     if (vms->secure) {
1904         create_secure_ram(vms, secure_sysmem, secure_tag_sysmem);
1905         create_uart(vms, VIRT_SECURE_UART, secure_sysmem, serial_hd(1));
1906     }
1907 
1908     if (tag_sysmem) {
1909         create_tag_ram(tag_sysmem, vms->memmap[VIRT_MEM].base,
1910                        machine->ram_size, "mach-virt.tag");
1911     }
1912 
1913     vms->highmem_ecam &= vms->highmem && (!firmware_loaded || aarch64);
1914 
1915     create_rtc(vms);
1916 
1917     create_pcie(vms);
1918 
1919     if (has_ged && aarch64 && firmware_loaded && virt_is_acpi_enabled(vms)) {
1920         vms->acpi_dev = create_acpi_ged(vms);
1921     } else {
1922         create_gpio(vms);
1923     }
1924 
1925      /* connect powerdown request */
1926      vms->powerdown_notifier.notify = virt_powerdown_req;
1927      qemu_register_powerdown_notifier(&vms->powerdown_notifier);
1928 
1929     /* Create mmio transports, so the user can create virtio backends
1930      * (which will be automatically plugged in to the transports). If
1931      * no backend is created the transport will just sit harmlessly idle.
1932      */
1933     create_virtio_devices(vms);
1934 
1935     vms->fw_cfg = create_fw_cfg(vms, &address_space_memory);
1936     rom_set_fw(vms->fw_cfg);
1937 
1938     create_platform_bus(vms);
1939 
1940     if (machine->nvdimms_state->is_enabled) {
1941         const struct AcpiGenericAddress arm_virt_nvdimm_acpi_dsmio = {
1942             .space_id = AML_AS_SYSTEM_MEMORY,
1943             .address = vms->memmap[VIRT_NVDIMM_ACPI].base,
1944             .bit_width = NVDIMM_ACPI_IO_LEN << 3
1945         };
1946 
1947         nvdimm_init_acpi_state(machine->nvdimms_state, sysmem,
1948                                arm_virt_nvdimm_acpi_dsmio,
1949                                vms->fw_cfg, OBJECT(vms));
1950     }
1951 
1952     vms->bootinfo.ram_size = machine->ram_size;
1953     vms->bootinfo.nb_cpus = smp_cpus;
1954     vms->bootinfo.board_id = -1;
1955     vms->bootinfo.loader_start = vms->memmap[VIRT_MEM].base;
1956     vms->bootinfo.get_dtb = machvirt_dtb;
1957     vms->bootinfo.skip_dtb_autoload = true;
1958     vms->bootinfo.firmware_loaded = firmware_loaded;
1959     arm_load_kernel(ARM_CPU(first_cpu), machine, &vms->bootinfo);
1960 
1961     vms->machine_done.notify = virt_machine_done;
1962     qemu_add_machine_init_done_notifier(&vms->machine_done);
1963 }
1964 
1965 static bool virt_get_secure(Object *obj, Error **errp)
1966 {
1967     VirtMachineState *vms = VIRT_MACHINE(obj);
1968 
1969     return vms->secure;
1970 }
1971 
1972 static void virt_set_secure(Object *obj, bool value, Error **errp)
1973 {
1974     VirtMachineState *vms = VIRT_MACHINE(obj);
1975 
1976     vms->secure = value;
1977 }
1978 
1979 static bool virt_get_virt(Object *obj, Error **errp)
1980 {
1981     VirtMachineState *vms = VIRT_MACHINE(obj);
1982 
1983     return vms->virt;
1984 }
1985 
1986 static void virt_set_virt(Object *obj, bool value, Error **errp)
1987 {
1988     VirtMachineState *vms = VIRT_MACHINE(obj);
1989 
1990     vms->virt = value;
1991 }
1992 
1993 static bool virt_get_highmem(Object *obj, Error **errp)
1994 {
1995     VirtMachineState *vms = VIRT_MACHINE(obj);
1996 
1997     return vms->highmem;
1998 }
1999 
2000 static void virt_set_highmem(Object *obj, bool value, Error **errp)
2001 {
2002     VirtMachineState *vms = VIRT_MACHINE(obj);
2003 
2004     vms->highmem = value;
2005 }
2006 
2007 static bool virt_get_its(Object *obj, Error **errp)
2008 {
2009     VirtMachineState *vms = VIRT_MACHINE(obj);
2010 
2011     return vms->its;
2012 }
2013 
2014 static void virt_set_its(Object *obj, bool value, Error **errp)
2015 {
2016     VirtMachineState *vms = VIRT_MACHINE(obj);
2017 
2018     vms->its = value;
2019 }
2020 
2021 bool virt_is_acpi_enabled(VirtMachineState *vms)
2022 {
2023     if (vms->acpi == ON_OFF_AUTO_OFF) {
2024         return false;
2025     }
2026     return true;
2027 }
2028 
2029 static void virt_get_acpi(Object *obj, Visitor *v, const char *name,
2030                           void *opaque, Error **errp)
2031 {
2032     VirtMachineState *vms = VIRT_MACHINE(obj);
2033     OnOffAuto acpi = vms->acpi;
2034 
2035     visit_type_OnOffAuto(v, name, &acpi, errp);
2036 }
2037 
2038 static void virt_set_acpi(Object *obj, Visitor *v, const char *name,
2039                           void *opaque, Error **errp)
2040 {
2041     VirtMachineState *vms = VIRT_MACHINE(obj);
2042 
2043     visit_type_OnOffAuto(v, name, &vms->acpi, errp);
2044 }
2045 
2046 static bool virt_get_ras(Object *obj, Error **errp)
2047 {
2048     VirtMachineState *vms = VIRT_MACHINE(obj);
2049 
2050     return vms->ras;
2051 }
2052 
2053 static void virt_set_ras(Object *obj, bool value, Error **errp)
2054 {
2055     VirtMachineState *vms = VIRT_MACHINE(obj);
2056 
2057     vms->ras = value;
2058 }
2059 
2060 static char *virt_get_gic_version(Object *obj, Error **errp)
2061 {
2062     VirtMachineState *vms = VIRT_MACHINE(obj);
2063     const char *val = vms->gic_version == VIRT_GIC_VERSION_3 ? "3" : "2";
2064 
2065     return g_strdup(val);
2066 }
2067 
2068 static void virt_set_gic_version(Object *obj, const char *value, Error **errp)
2069 {
2070     VirtMachineState *vms = VIRT_MACHINE(obj);
2071 
2072     if (!strcmp(value, "3")) {
2073         vms->gic_version = VIRT_GIC_VERSION_3;
2074     } else if (!strcmp(value, "2")) {
2075         vms->gic_version = VIRT_GIC_VERSION_2;
2076     } else if (!strcmp(value, "host")) {
2077         vms->gic_version = VIRT_GIC_VERSION_HOST; /* Will probe later */
2078     } else if (!strcmp(value, "max")) {
2079         vms->gic_version = VIRT_GIC_VERSION_MAX; /* Will probe later */
2080     } else {
2081         error_setg(errp, "Invalid gic-version value");
2082         error_append_hint(errp, "Valid values are 3, 2, host, max.\n");
2083     }
2084 }
2085 
2086 static char *virt_get_iommu(Object *obj, Error **errp)
2087 {
2088     VirtMachineState *vms = VIRT_MACHINE(obj);
2089 
2090     switch (vms->iommu) {
2091     case VIRT_IOMMU_NONE:
2092         return g_strdup("none");
2093     case VIRT_IOMMU_SMMUV3:
2094         return g_strdup("smmuv3");
2095     default:
2096         g_assert_not_reached();
2097     }
2098 }
2099 
2100 static void virt_set_iommu(Object *obj, const char *value, Error **errp)
2101 {
2102     VirtMachineState *vms = VIRT_MACHINE(obj);
2103 
2104     if (!strcmp(value, "smmuv3")) {
2105         vms->iommu = VIRT_IOMMU_SMMUV3;
2106     } else if (!strcmp(value, "none")) {
2107         vms->iommu = VIRT_IOMMU_NONE;
2108     } else {
2109         error_setg(errp, "Invalid iommu value");
2110         error_append_hint(errp, "Valid values are none, smmuv3.\n");
2111     }
2112 }
2113 
2114 static CpuInstanceProperties
2115 virt_cpu_index_to_props(MachineState *ms, unsigned cpu_index)
2116 {
2117     MachineClass *mc = MACHINE_GET_CLASS(ms);
2118     const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
2119 
2120     assert(cpu_index < possible_cpus->len);
2121     return possible_cpus->cpus[cpu_index].props;
2122 }
2123 
2124 static int64_t virt_get_default_cpu_node_id(const MachineState *ms, int idx)
2125 {
2126     return idx % ms->numa_state->num_nodes;
2127 }
2128 
2129 static const CPUArchIdList *virt_possible_cpu_arch_ids(MachineState *ms)
2130 {
2131     int n;
2132     unsigned int max_cpus = ms->smp.max_cpus;
2133     VirtMachineState *vms = VIRT_MACHINE(ms);
2134 
2135     if (ms->possible_cpus) {
2136         assert(ms->possible_cpus->len == max_cpus);
2137         return ms->possible_cpus;
2138     }
2139 
2140     ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
2141                                   sizeof(CPUArchId) * max_cpus);
2142     ms->possible_cpus->len = max_cpus;
2143     for (n = 0; n < ms->possible_cpus->len; n++) {
2144         ms->possible_cpus->cpus[n].type = ms->cpu_type;
2145         ms->possible_cpus->cpus[n].arch_id =
2146             virt_cpu_mp_affinity(vms, n);
2147         ms->possible_cpus->cpus[n].props.has_thread_id = true;
2148         ms->possible_cpus->cpus[n].props.thread_id = n;
2149     }
2150     return ms->possible_cpus;
2151 }
2152 
2153 static void virt_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
2154                                  Error **errp)
2155 {
2156     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2157     const MachineState *ms = MACHINE(hotplug_dev);
2158     const bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
2159 
2160     if (!vms->acpi_dev) {
2161         error_setg(errp,
2162                    "memory hotplug is not enabled: missing acpi-ged device");
2163         return;
2164     }
2165 
2166     if (is_nvdimm && !ms->nvdimms_state->is_enabled) {
2167         error_setg(errp, "nvdimm is not enabled: add 'nvdimm=on' to '-M'");
2168         return;
2169     }
2170 
2171     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev), NULL, errp);
2172 }
2173 
2174 static void virt_memory_plug(HotplugHandler *hotplug_dev,
2175                              DeviceState *dev, Error **errp)
2176 {
2177     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2178     MachineState *ms = MACHINE(hotplug_dev);
2179     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
2180     Error *local_err = NULL;
2181 
2182     pc_dimm_plug(PC_DIMM(dev), MACHINE(vms), &local_err);
2183     if (local_err) {
2184         goto out;
2185     }
2186 
2187     if (is_nvdimm) {
2188         nvdimm_plug(ms->nvdimms_state);
2189     }
2190 
2191     hotplug_handler_plug(HOTPLUG_HANDLER(vms->acpi_dev),
2192                          dev, &error_abort);
2193 
2194 out:
2195     error_propagate(errp, local_err);
2196 }
2197 
2198 static void virt_machine_device_pre_plug_cb(HotplugHandler *hotplug_dev,
2199                                             DeviceState *dev, Error **errp)
2200 {
2201     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2202         virt_memory_pre_plug(hotplug_dev, dev, errp);
2203     }
2204 }
2205 
2206 static void virt_machine_device_plug_cb(HotplugHandler *hotplug_dev,
2207                                         DeviceState *dev, Error **errp)
2208 {
2209     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2210 
2211     if (vms->platform_bus_dev) {
2212         if (object_dynamic_cast(OBJECT(dev), TYPE_SYS_BUS_DEVICE)) {
2213             platform_bus_link_device(PLATFORM_BUS_DEVICE(vms->platform_bus_dev),
2214                                      SYS_BUS_DEVICE(dev));
2215         }
2216     }
2217     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2218         virt_memory_plug(hotplug_dev, dev, errp);
2219     }
2220     if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
2221         PCIDevice *pdev = PCI_DEVICE(dev);
2222 
2223         vms->iommu = VIRT_IOMMU_VIRTIO;
2224         vms->virtio_iommu_bdf = pci_get_bdf(pdev);
2225         create_virtio_iommu_dt_bindings(vms);
2226     }
2227 }
2228 
2229 static void virt_dimm_unplug_request(HotplugHandler *hotplug_dev,
2230                                      DeviceState *dev, Error **errp)
2231 {
2232     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2233     Error *local_err = NULL;
2234 
2235     if (!vms->acpi_dev) {
2236         error_setg(&local_err,
2237                    "memory hotplug is not enabled: missing acpi-ged device");
2238         goto out;
2239     }
2240 
2241     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
2242         error_setg(&local_err,
2243                    "nvdimm device hot unplug is not supported yet.");
2244         goto out;
2245     }
2246 
2247     hotplug_handler_unplug_request(HOTPLUG_HANDLER(vms->acpi_dev), dev,
2248                                    &local_err);
2249 out:
2250     error_propagate(errp, local_err);
2251 }
2252 
2253 static void virt_dimm_unplug(HotplugHandler *hotplug_dev,
2254                              DeviceState *dev, Error **errp)
2255 {
2256     VirtMachineState *vms = VIRT_MACHINE(hotplug_dev);
2257     Error *local_err = NULL;
2258 
2259     hotplug_handler_unplug(HOTPLUG_HANDLER(vms->acpi_dev), dev, &local_err);
2260     if (local_err) {
2261         goto out;
2262     }
2263 
2264     pc_dimm_unplug(PC_DIMM(dev), MACHINE(vms));
2265     qdev_unrealize(dev);
2266 
2267 out:
2268     error_propagate(errp, local_err);
2269 }
2270 
2271 static void virt_machine_device_unplug_request_cb(HotplugHandler *hotplug_dev,
2272                                           DeviceState *dev, Error **errp)
2273 {
2274     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2275         virt_dimm_unplug_request(hotplug_dev, dev, errp);
2276     } else {
2277         error_setg(errp, "device unplug request for unsupported device"
2278                    " type: %s", object_get_typename(OBJECT(dev)));
2279     }
2280 }
2281 
2282 static void virt_machine_device_unplug_cb(HotplugHandler *hotplug_dev,
2283                                           DeviceState *dev, Error **errp)
2284 {
2285     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
2286         virt_dimm_unplug(hotplug_dev, dev, errp);
2287     } else {
2288         error_setg(errp, "virt: device unplug for unsupported device"
2289                    " type: %s", object_get_typename(OBJECT(dev)));
2290     }
2291 }
2292 
2293 static HotplugHandler *virt_machine_get_hotplug_handler(MachineState *machine,
2294                                                         DeviceState *dev)
2295 {
2296     if (object_dynamic_cast(OBJECT(dev), TYPE_SYS_BUS_DEVICE) ||
2297        (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM))) {
2298         return HOTPLUG_HANDLER(machine);
2299     }
2300     if (object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI)) {
2301         VirtMachineState *vms = VIRT_MACHINE(machine);
2302 
2303         if (!vms->bootinfo.firmware_loaded || !virt_is_acpi_enabled(vms)) {
2304             return HOTPLUG_HANDLER(machine);
2305         }
2306     }
2307     return NULL;
2308 }
2309 
2310 /*
2311  * for arm64 kvm_type [7-0] encodes the requested number of bits
2312  * in the IPA address space
2313  */
2314 static int virt_kvm_type(MachineState *ms, const char *type_str)
2315 {
2316     VirtMachineState *vms = VIRT_MACHINE(ms);
2317     int max_vm_pa_size = kvm_arm_get_max_vm_ipa_size(ms);
2318     int requested_pa_size;
2319 
2320     /* we freeze the memory map to compute the highest gpa */
2321     virt_set_memmap(vms);
2322 
2323     requested_pa_size = 64 - clz64(vms->highest_gpa);
2324 
2325     if (requested_pa_size > max_vm_pa_size) {
2326         error_report("-m and ,maxmem option values "
2327                      "require an IPA range (%d bits) larger than "
2328                      "the one supported by the host (%d bits)",
2329                      requested_pa_size, max_vm_pa_size);
2330        exit(1);
2331     }
2332     /*
2333      * By default we return 0 which corresponds to an implicit legacy
2334      * 40b IPA setting. Otherwise we return the actual requested PA
2335      * logsize
2336      */
2337     return requested_pa_size > 40 ? requested_pa_size : 0;
2338 }
2339 
2340 static void virt_machine_class_init(ObjectClass *oc, void *data)
2341 {
2342     MachineClass *mc = MACHINE_CLASS(oc);
2343     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
2344 
2345     mc->init = machvirt_init;
2346     /* Start with max_cpus set to 512, which is the maximum supported by KVM.
2347      * The value may be reduced later when we have more information about the
2348      * configuration of the particular instance.
2349      */
2350     mc->max_cpus = 512;
2351     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_VFIO_CALXEDA_XGMAC);
2352     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_VFIO_AMD_XGBE);
2353     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_RAMFB_DEVICE);
2354     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_VFIO_PLATFORM);
2355     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
2356     mc->block_default_type = IF_VIRTIO;
2357     mc->no_cdrom = 1;
2358     mc->pci_allow_0_address = true;
2359     /* We know we will never create a pre-ARMv7 CPU which needs 1K pages */
2360     mc->minimum_page_bits = 12;
2361     mc->possible_cpu_arch_ids = virt_possible_cpu_arch_ids;
2362     mc->cpu_index_to_instance_props = virt_cpu_index_to_props;
2363     mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-a15");
2364     mc->get_default_cpu_node_id = virt_get_default_cpu_node_id;
2365     mc->kvm_type = virt_kvm_type;
2366     assert(!mc->get_hotplug_handler);
2367     mc->get_hotplug_handler = virt_machine_get_hotplug_handler;
2368     hc->pre_plug = virt_machine_device_pre_plug_cb;
2369     hc->plug = virt_machine_device_plug_cb;
2370     hc->unplug_request = virt_machine_device_unplug_request_cb;
2371     hc->unplug = virt_machine_device_unplug_cb;
2372     mc->nvdimm_supported = true;
2373     mc->auto_enable_numa_with_memhp = true;
2374     mc->default_ram_id = "mach-virt.ram";
2375 
2376     object_class_property_add(oc, "acpi", "OnOffAuto",
2377         virt_get_acpi, virt_set_acpi,
2378         NULL, NULL);
2379     object_class_property_set_description(oc, "acpi",
2380         "Enable ACPI");
2381 }
2382 
2383 static void virt_instance_init(Object *obj)
2384 {
2385     VirtMachineState *vms = VIRT_MACHINE(obj);
2386     VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);
2387 
2388     /* EL3 is disabled by default on virt: this makes us consistent
2389      * between KVM and TCG for this board, and it also allows us to
2390      * boot UEFI blobs which assume no TrustZone support.
2391      */
2392     vms->secure = false;
2393     object_property_add_bool(obj, "secure", virt_get_secure,
2394                              virt_set_secure);
2395     object_property_set_description(obj, "secure",
2396                                     "Set on/off to enable/disable the ARM "
2397                                     "Security Extensions (TrustZone)");
2398 
2399     /* EL2 is also disabled by default, for similar reasons */
2400     vms->virt = false;
2401     object_property_add_bool(obj, "virtualization", virt_get_virt,
2402                              virt_set_virt);
2403     object_property_set_description(obj, "virtualization",
2404                                     "Set on/off to enable/disable emulating a "
2405                                     "guest CPU which implements the ARM "
2406                                     "Virtualization Extensions");
2407 
2408     /* High memory is enabled by default */
2409     vms->highmem = true;
2410     object_property_add_bool(obj, "highmem", virt_get_highmem,
2411                              virt_set_highmem);
2412     object_property_set_description(obj, "highmem",
2413                                     "Set on/off to enable/disable using "
2414                                     "physical address space above 32 bits");
2415     vms->gic_version = VIRT_GIC_VERSION_NOSEL;
2416     object_property_add_str(obj, "gic-version", virt_get_gic_version,
2417                         virt_set_gic_version);
2418     object_property_set_description(obj, "gic-version",
2419                                     "Set GIC version. "
2420                                     "Valid values are 2, 3, host and max");
2421 
2422     vms->highmem_ecam = !vmc->no_highmem_ecam;
2423 
2424     if (vmc->no_its) {
2425         vms->its = false;
2426     } else {
2427         /* Default allows ITS instantiation */
2428         vms->its = true;
2429         object_property_add_bool(obj, "its", virt_get_its,
2430                                  virt_set_its);
2431         object_property_set_description(obj, "its",
2432                                         "Set on/off to enable/disable "
2433                                         "ITS instantiation");
2434     }
2435 
2436     /* Default disallows iommu instantiation */
2437     vms->iommu = VIRT_IOMMU_NONE;
2438     object_property_add_str(obj, "iommu", virt_get_iommu, virt_set_iommu);
2439     object_property_set_description(obj, "iommu",
2440                                     "Set the IOMMU type. "
2441                                     "Valid values are none and smmuv3");
2442 
2443     /* Default disallows RAS instantiation */
2444     vms->ras = false;
2445     object_property_add_bool(obj, "ras", virt_get_ras,
2446                              virt_set_ras);
2447     object_property_set_description(obj, "ras",
2448                                     "Set on/off to enable/disable reporting host memory errors "
2449                                     "to a KVM guest using ACPI and guest external abort exceptions");
2450 
2451     vms->irqmap = a15irqmap;
2452 
2453     virt_flash_create(vms);
2454 }
2455 
2456 static const TypeInfo virt_machine_info = {
2457     .name          = TYPE_VIRT_MACHINE,
2458     .parent        = TYPE_MACHINE,
2459     .abstract      = true,
2460     .instance_size = sizeof(VirtMachineState),
2461     .class_size    = sizeof(VirtMachineClass),
2462     .class_init    = virt_machine_class_init,
2463     .instance_init = virt_instance_init,
2464     .interfaces = (InterfaceInfo[]) {
2465          { TYPE_HOTPLUG_HANDLER },
2466          { }
2467     },
2468 };
2469 
2470 static void machvirt_machine_init(void)
2471 {
2472     type_register_static(&virt_machine_info);
2473 }
2474 type_init(machvirt_machine_init);
2475 
2476 static void virt_machine_5_1_options(MachineClass *mc)
2477 {
2478 }
2479 DEFINE_VIRT_MACHINE_AS_LATEST(5, 1)
2480 
2481 static void virt_machine_5_0_options(MachineClass *mc)
2482 {
2483     virt_machine_5_1_options(mc);
2484     compat_props_add(mc->compat_props, hw_compat_5_0, hw_compat_5_0_len);
2485     mc->numa_mem_supported = true;
2486 }
2487 DEFINE_VIRT_MACHINE(5, 0)
2488 
2489 static void virt_machine_4_2_options(MachineClass *mc)
2490 {
2491     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2492 
2493     virt_machine_5_0_options(mc);
2494     compat_props_add(mc->compat_props, hw_compat_4_2, hw_compat_4_2_len);
2495     vmc->kvm_no_adjvtime = true;
2496 }
2497 DEFINE_VIRT_MACHINE(4, 2)
2498 
2499 static void virt_machine_4_1_options(MachineClass *mc)
2500 {
2501     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2502 
2503     virt_machine_4_2_options(mc);
2504     compat_props_add(mc->compat_props, hw_compat_4_1, hw_compat_4_1_len);
2505     vmc->no_ged = true;
2506     mc->auto_enable_numa_with_memhp = false;
2507 }
2508 DEFINE_VIRT_MACHINE(4, 1)
2509 
2510 static void virt_machine_4_0_options(MachineClass *mc)
2511 {
2512     virt_machine_4_1_options(mc);
2513     compat_props_add(mc->compat_props, hw_compat_4_0, hw_compat_4_0_len);
2514 }
2515 DEFINE_VIRT_MACHINE(4, 0)
2516 
2517 static void virt_machine_3_1_options(MachineClass *mc)
2518 {
2519     virt_machine_4_0_options(mc);
2520     compat_props_add(mc->compat_props, hw_compat_3_1, hw_compat_3_1_len);
2521 }
2522 DEFINE_VIRT_MACHINE(3, 1)
2523 
2524 static void virt_machine_3_0_options(MachineClass *mc)
2525 {
2526     virt_machine_3_1_options(mc);
2527     compat_props_add(mc->compat_props, hw_compat_3_0, hw_compat_3_0_len);
2528 }
2529 DEFINE_VIRT_MACHINE(3, 0)
2530 
2531 static void virt_machine_2_12_options(MachineClass *mc)
2532 {
2533     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2534 
2535     virt_machine_3_0_options(mc);
2536     compat_props_add(mc->compat_props, hw_compat_2_12, hw_compat_2_12_len);
2537     vmc->no_highmem_ecam = true;
2538     mc->max_cpus = 255;
2539 }
2540 DEFINE_VIRT_MACHINE(2, 12)
2541 
2542 static void virt_machine_2_11_options(MachineClass *mc)
2543 {
2544     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2545 
2546     virt_machine_2_12_options(mc);
2547     compat_props_add(mc->compat_props, hw_compat_2_11, hw_compat_2_11_len);
2548     vmc->smbios_old_sys_ver = true;
2549 }
2550 DEFINE_VIRT_MACHINE(2, 11)
2551 
2552 static void virt_machine_2_10_options(MachineClass *mc)
2553 {
2554     virt_machine_2_11_options(mc);
2555     compat_props_add(mc->compat_props, hw_compat_2_10, hw_compat_2_10_len);
2556     /* before 2.11 we never faulted accesses to bad addresses */
2557     mc->ignore_memory_transaction_failures = true;
2558 }
2559 DEFINE_VIRT_MACHINE(2, 10)
2560 
2561 static void virt_machine_2_9_options(MachineClass *mc)
2562 {
2563     virt_machine_2_10_options(mc);
2564     compat_props_add(mc->compat_props, hw_compat_2_9, hw_compat_2_9_len);
2565 }
2566 DEFINE_VIRT_MACHINE(2, 9)
2567 
2568 static void virt_machine_2_8_options(MachineClass *mc)
2569 {
2570     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2571 
2572     virt_machine_2_9_options(mc);
2573     compat_props_add(mc->compat_props, hw_compat_2_8, hw_compat_2_8_len);
2574     /* For 2.8 and earlier we falsely claimed in the DT that
2575      * our timers were edge-triggered, not level-triggered.
2576      */
2577     vmc->claim_edge_triggered_timers = true;
2578 }
2579 DEFINE_VIRT_MACHINE(2, 8)
2580 
2581 static void virt_machine_2_7_options(MachineClass *mc)
2582 {
2583     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2584 
2585     virt_machine_2_8_options(mc);
2586     compat_props_add(mc->compat_props, hw_compat_2_7, hw_compat_2_7_len);
2587     /* ITS was introduced with 2.8 */
2588     vmc->no_its = true;
2589     /* Stick with 1K pages for migration compatibility */
2590     mc->minimum_page_bits = 0;
2591 }
2592 DEFINE_VIRT_MACHINE(2, 7)
2593 
2594 static void virt_machine_2_6_options(MachineClass *mc)
2595 {
2596     VirtMachineClass *vmc = VIRT_MACHINE_CLASS(OBJECT_CLASS(mc));
2597 
2598     virt_machine_2_7_options(mc);
2599     compat_props_add(mc->compat_props, hw_compat_2_6, hw_compat_2_6_len);
2600     vmc->disallow_affinity_adjustment = true;
2601     /* Disable PMU for 2.6 as PMU support was first introduced in 2.7 */
2602     vmc->no_pmu = true;
2603 }
2604 DEFINE_VIRT_MACHINE(2, 6)
2605