xref: /openbmc/qemu/hw/loongarch/virt.c (revision c76c86fb)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3  * QEMU loongson 3a5000 develop board emulation
4  *
5  * Copyright (c) 2021 Loongson Technology Corporation Limited
6  */
7 #include "qemu/osdep.h"
8 #include "qemu/units.h"
9 #include "qemu/datadir.h"
10 #include "qapi/error.h"
11 #include "hw/boards.h"
12 #include "hw/char/serial-mm.h"
13 #include "sysemu/kvm.h"
14 #include "sysemu/tcg.h"
15 #include "sysemu/sysemu.h"
16 #include "sysemu/qtest.h"
17 #include "sysemu/runstate.h"
18 #include "sysemu/reset.h"
19 #include "sysemu/rtc.h"
20 #include "hw/loongarch/virt.h"
21 #include "exec/address-spaces.h"
22 #include "hw/irq.h"
23 #include "net/net.h"
24 #include "hw/loader.h"
25 #include "elf.h"
26 #include "hw/intc/loongarch_ipi.h"
27 #include "hw/intc/loongarch_extioi.h"
28 #include "hw/intc/loongarch_pch_pic.h"
29 #include "hw/intc/loongarch_pch_msi.h"
30 #include "hw/pci-host/ls7a.h"
31 #include "hw/pci-host/gpex.h"
32 #include "hw/misc/unimp.h"
33 #include "hw/loongarch/fw_cfg.h"
34 #include "target/loongarch/cpu.h"
35 #include "hw/firmware/smbios.h"
36 #include "hw/acpi/aml-build.h"
37 #include "qapi/qapi-visit-common.h"
38 #include "hw/acpi/generic_event_device.h"
39 #include "hw/mem/nvdimm.h"
40 #include "sysemu/device_tree.h"
41 #include <libfdt.h>
42 #include "hw/core/sysbus-fdt.h"
43 #include "hw/platform-bus.h"
44 #include "hw/display/ramfb.h"
45 #include "hw/mem/pc-dimm.h"
46 #include "sysemu/tpm.h"
47 #include "sysemu/block-backend.h"
48 #include "hw/block/flash.h"
49 #include "hw/virtio/virtio-iommu.h"
50 #include "qemu/error-report.h"
51 #include "qemu/guest-random.h"
52 
53 static bool virt_is_veiointc_enabled(LoongArchVirtMachineState *lvms)
54 {
55     if (lvms->veiointc == ON_OFF_AUTO_OFF) {
56         return false;
57     }
58     return true;
59 }
60 
61 static void virt_get_veiointc(Object *obj, Visitor *v, const char *name,
62                               void *opaque, Error **errp)
63 {
64     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(obj);
65     OnOffAuto veiointc = lvms->veiointc;
66 
67     visit_type_OnOffAuto(v, name, &veiointc, errp);
68 }
69 
70 static void virt_set_veiointc(Object *obj, Visitor *v, const char *name,
71                               void *opaque, Error **errp)
72 {
73     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(obj);
74 
75     visit_type_OnOffAuto(v, name, &lvms->veiointc, errp);
76 }
77 
78 static PFlashCFI01 *virt_flash_create1(LoongArchVirtMachineState *lvms,
79                                        const char *name,
80                                        const char *alias_prop_name)
81 {
82     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI01);
83 
84     qdev_prop_set_uint64(dev, "sector-length", VIRT_FLASH_SECTOR_SIZE);
85     qdev_prop_set_uint8(dev, "width", 4);
86     qdev_prop_set_uint8(dev, "device-width", 2);
87     qdev_prop_set_bit(dev, "big-endian", false);
88     qdev_prop_set_uint16(dev, "id0", 0x89);
89     qdev_prop_set_uint16(dev, "id1", 0x18);
90     qdev_prop_set_uint16(dev, "id2", 0x00);
91     qdev_prop_set_uint16(dev, "id3", 0x00);
92     qdev_prop_set_string(dev, "name", name);
93     object_property_add_child(OBJECT(lvms), name, OBJECT(dev));
94     object_property_add_alias(OBJECT(lvms), alias_prop_name,
95                               OBJECT(dev), "drive");
96     return PFLASH_CFI01(dev);
97 }
98 
99 static void virt_flash_create(LoongArchVirtMachineState *lvms)
100 {
101     lvms->flash[0] = virt_flash_create1(lvms, "virt.flash0", "pflash0");
102     lvms->flash[1] = virt_flash_create1(lvms, "virt.flash1", "pflash1");
103 }
104 
105 static void virt_flash_map1(PFlashCFI01 *flash,
106                             hwaddr base, hwaddr size,
107                             MemoryRegion *sysmem)
108 {
109     DeviceState *dev = DEVICE(flash);
110     BlockBackend *blk;
111     hwaddr real_size = size;
112 
113     blk = pflash_cfi01_get_blk(flash);
114     if (blk) {
115         real_size = blk_getlength(blk);
116         assert(real_size && real_size <= size);
117     }
118 
119     assert(QEMU_IS_ALIGNED(real_size, VIRT_FLASH_SECTOR_SIZE));
120     assert(real_size / VIRT_FLASH_SECTOR_SIZE <= UINT32_MAX);
121 
122     qdev_prop_set_uint32(dev, "num-blocks", real_size / VIRT_FLASH_SECTOR_SIZE);
123     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
124     memory_region_add_subregion(sysmem, base,
125                                 sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 0));
126 }
127 
128 static void virt_flash_map(LoongArchVirtMachineState *lvms,
129                            MemoryRegion *sysmem)
130 {
131     PFlashCFI01 *flash0 = lvms->flash[0];
132     PFlashCFI01 *flash1 = lvms->flash[1];
133 
134     virt_flash_map1(flash0, VIRT_FLASH0_BASE, VIRT_FLASH0_SIZE, sysmem);
135     virt_flash_map1(flash1, VIRT_FLASH1_BASE, VIRT_FLASH1_SIZE, sysmem);
136 }
137 
138 static void fdt_add_cpuic_node(LoongArchVirtMachineState *lvms,
139                                uint32_t *cpuintc_phandle)
140 {
141     MachineState *ms = MACHINE(lvms);
142     char *nodename;
143 
144     *cpuintc_phandle = qemu_fdt_alloc_phandle(ms->fdt);
145     nodename = g_strdup_printf("/cpuic");
146     qemu_fdt_add_subnode(ms->fdt, nodename);
147     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", *cpuintc_phandle);
148     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
149                             "loongson,cpu-interrupt-controller");
150     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-controller", NULL, 0);
151     qemu_fdt_setprop_cell(ms->fdt, nodename, "#interrupt-cells", 1);
152     g_free(nodename);
153 }
154 
155 static void fdt_add_eiointc_node(LoongArchVirtMachineState *lvms,
156                                   uint32_t *cpuintc_phandle,
157                                   uint32_t *eiointc_phandle)
158 {
159     MachineState *ms = MACHINE(lvms);
160     char *nodename;
161     hwaddr extioi_base = APIC_BASE;
162     hwaddr extioi_size = EXTIOI_SIZE;
163 
164     *eiointc_phandle = qemu_fdt_alloc_phandle(ms->fdt);
165     nodename = g_strdup_printf("/eiointc@%" PRIx64, extioi_base);
166     qemu_fdt_add_subnode(ms->fdt, nodename);
167     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", *eiointc_phandle);
168     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
169                             "loongson,ls2k2000-eiointc");
170     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-controller", NULL, 0);
171     qemu_fdt_setprop_cell(ms->fdt, nodename, "#interrupt-cells", 1);
172     qemu_fdt_setprop_cell(ms->fdt, nodename, "interrupt-parent",
173                           *cpuintc_phandle);
174     qemu_fdt_setprop_cell(ms->fdt, nodename, "interrupts", 3);
175     qemu_fdt_setprop_cells(ms->fdt, nodename, "reg", 0x0,
176                            extioi_base, 0x0, extioi_size);
177     g_free(nodename);
178 }
179 
180 static void fdt_add_pch_pic_node(LoongArchVirtMachineState *lvms,
181                                  uint32_t *eiointc_phandle,
182                                  uint32_t *pch_pic_phandle)
183 {
184     MachineState *ms = MACHINE(lvms);
185     char *nodename;
186     hwaddr pch_pic_base = VIRT_PCH_REG_BASE;
187     hwaddr pch_pic_size = VIRT_PCH_REG_SIZE;
188 
189     *pch_pic_phandle = qemu_fdt_alloc_phandle(ms->fdt);
190     nodename = g_strdup_printf("/platic@%" PRIx64, pch_pic_base);
191     qemu_fdt_add_subnode(ms->fdt, nodename);
192     qemu_fdt_setprop_cell(ms->fdt,  nodename, "phandle", *pch_pic_phandle);
193     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
194                             "loongson,pch-pic-1.0");
195     qemu_fdt_setprop_cells(ms->fdt, nodename, "reg", 0,
196                            pch_pic_base, 0, pch_pic_size);
197     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-controller", NULL, 0);
198     qemu_fdt_setprop_cell(ms->fdt, nodename, "#interrupt-cells", 2);
199     qemu_fdt_setprop_cell(ms->fdt, nodename, "interrupt-parent",
200                           *eiointc_phandle);
201     qemu_fdt_setprop_cell(ms->fdt, nodename, "loongson,pic-base-vec", 0);
202     g_free(nodename);
203 }
204 
205 static void fdt_add_pch_msi_node(LoongArchVirtMachineState *lvms,
206                                  uint32_t *eiointc_phandle,
207                                  uint32_t *pch_msi_phandle)
208 {
209     MachineState *ms = MACHINE(lvms);
210     char *nodename;
211     hwaddr pch_msi_base = VIRT_PCH_MSI_ADDR_LOW;
212     hwaddr pch_msi_size = VIRT_PCH_MSI_SIZE;
213 
214     *pch_msi_phandle = qemu_fdt_alloc_phandle(ms->fdt);
215     nodename = g_strdup_printf("/msi@%" PRIx64, pch_msi_base);
216     qemu_fdt_add_subnode(ms->fdt, nodename);
217     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", *pch_msi_phandle);
218     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
219                             "loongson,pch-msi-1.0");
220     qemu_fdt_setprop_cells(ms->fdt, nodename, "reg",
221                            0, pch_msi_base,
222                            0, pch_msi_size);
223     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-controller", NULL, 0);
224     qemu_fdt_setprop_cell(ms->fdt, nodename, "interrupt-parent",
225                           *eiointc_phandle);
226     qemu_fdt_setprop_cell(ms->fdt, nodename, "loongson,msi-base-vec",
227                           VIRT_PCH_PIC_IRQ_NUM);
228     qemu_fdt_setprop_cell(ms->fdt, nodename, "loongson,msi-num-vecs",
229                           EXTIOI_IRQS - VIRT_PCH_PIC_IRQ_NUM);
230     g_free(nodename);
231 }
232 
233 static void fdt_add_flash_node(LoongArchVirtMachineState *lvms)
234 {
235     MachineState *ms = MACHINE(lvms);
236     char *nodename;
237     MemoryRegion *flash_mem;
238 
239     hwaddr flash0_base;
240     hwaddr flash0_size;
241 
242     hwaddr flash1_base;
243     hwaddr flash1_size;
244 
245     flash_mem = pflash_cfi01_get_memory(lvms->flash[0]);
246     flash0_base = flash_mem->addr;
247     flash0_size = memory_region_size(flash_mem);
248 
249     flash_mem = pflash_cfi01_get_memory(lvms->flash[1]);
250     flash1_base = flash_mem->addr;
251     flash1_size = memory_region_size(flash_mem);
252 
253     nodename = g_strdup_printf("/flash@%" PRIx64, flash0_base);
254     qemu_fdt_add_subnode(ms->fdt, nodename);
255     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "cfi-flash");
256     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
257                                  2, flash0_base, 2, flash0_size,
258                                  2, flash1_base, 2, flash1_size);
259     qemu_fdt_setprop_cell(ms->fdt, nodename, "bank-width", 4);
260     g_free(nodename);
261 }
262 
263 static void fdt_add_rtc_node(LoongArchVirtMachineState *lvms,
264                              uint32_t *pch_pic_phandle)
265 {
266     char *nodename;
267     hwaddr base = VIRT_RTC_REG_BASE;
268     hwaddr size = VIRT_RTC_LEN;
269     MachineState *ms = MACHINE(lvms);
270 
271     nodename = g_strdup_printf("/rtc@%" PRIx64, base);
272     qemu_fdt_add_subnode(ms->fdt, nodename);
273     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
274                             "loongson,ls7a-rtc");
275     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg", 2, base, 2, size);
276     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts",
277                            VIRT_RTC_IRQ - VIRT_GSI_BASE , 0x4);
278     qemu_fdt_setprop_cell(ms->fdt, nodename, "interrupt-parent",
279                           *pch_pic_phandle);
280     g_free(nodename);
281 }
282 
283 static void fdt_add_uart_node(LoongArchVirtMachineState *lvms,
284                               uint32_t *pch_pic_phandle, hwaddr base,
285                               int irq, bool chosen)
286 {
287     char *nodename;
288     hwaddr size = VIRT_UART_SIZE;
289     MachineState *ms = MACHINE(lvms);
290 
291     nodename = g_strdup_printf("/serial@%" PRIx64, base);
292     qemu_fdt_add_subnode(ms->fdt, nodename);
293     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "ns16550a");
294     qemu_fdt_setprop_cells(ms->fdt, nodename, "reg", 0x0, base, 0x0, size);
295     qemu_fdt_setprop_cell(ms->fdt, nodename, "clock-frequency", 100000000);
296     if (chosen)
297         qemu_fdt_setprop_string(ms->fdt, "/chosen", "stdout-path", nodename);
298     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupts", irq, 0x4);
299     qemu_fdt_setprop_cell(ms->fdt, nodename, "interrupt-parent",
300                           *pch_pic_phandle);
301     g_free(nodename);
302 }
303 
304 static void create_fdt(LoongArchVirtMachineState *lvms)
305 {
306     MachineState *ms = MACHINE(lvms);
307     uint8_t rng_seed[32];
308 
309     ms->fdt = create_device_tree(&lvms->fdt_size);
310     if (!ms->fdt) {
311         error_report("create_device_tree() failed");
312         exit(1);
313     }
314 
315     /* Header */
316     qemu_fdt_setprop_string(ms->fdt, "/", "compatible",
317                             "linux,dummy-loongson3");
318     qemu_fdt_setprop_cell(ms->fdt, "/", "#address-cells", 0x2);
319     qemu_fdt_setprop_cell(ms->fdt, "/", "#size-cells", 0x2);
320     qemu_fdt_add_subnode(ms->fdt, "/chosen");
321 
322     /* Pass seed to RNG */
323     qemu_guest_getrandom_nofail(rng_seed, sizeof(rng_seed));
324     qemu_fdt_setprop(ms->fdt, "/chosen", "rng-seed", rng_seed, sizeof(rng_seed));
325 }
326 
327 static void fdt_add_cpu_nodes(const LoongArchVirtMachineState *lvms)
328 {
329     int num;
330     const MachineState *ms = MACHINE(lvms);
331     int smp_cpus = ms->smp.cpus;
332 
333     qemu_fdt_add_subnode(ms->fdt, "/cpus");
334     qemu_fdt_setprop_cell(ms->fdt, "/cpus", "#address-cells", 0x1);
335     qemu_fdt_setprop_cell(ms->fdt, "/cpus", "#size-cells", 0x0);
336 
337     /* cpu nodes */
338     for (num = smp_cpus - 1; num >= 0; num--) {
339         char *nodename = g_strdup_printf("/cpus/cpu@%d", num);
340         LoongArchCPU *cpu = LOONGARCH_CPU(qemu_get_cpu(num));
341         CPUState *cs = CPU(cpu);
342 
343         qemu_fdt_add_subnode(ms->fdt, nodename);
344         qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "cpu");
345         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
346                                 cpu->dtb_compatible);
347         if (ms->possible_cpus->cpus[cs->cpu_index].props.has_node_id) {
348             qemu_fdt_setprop_cell(ms->fdt, nodename, "numa-node-id",
349                 ms->possible_cpus->cpus[cs->cpu_index].props.node_id);
350         }
351         qemu_fdt_setprop_cell(ms->fdt, nodename, "reg", num);
352         qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle",
353                               qemu_fdt_alloc_phandle(ms->fdt));
354         g_free(nodename);
355     }
356 
357     /*cpu map */
358     qemu_fdt_add_subnode(ms->fdt, "/cpus/cpu-map");
359 
360     for (num = smp_cpus - 1; num >= 0; num--) {
361         char *cpu_path = g_strdup_printf("/cpus/cpu@%d", num);
362         char *map_path;
363 
364         if (ms->smp.threads > 1) {
365             map_path = g_strdup_printf(
366                 "/cpus/cpu-map/socket%d/core%d/thread%d",
367                 num / (ms->smp.cores * ms->smp.threads),
368                 (num / ms->smp.threads) % ms->smp.cores,
369                 num % ms->smp.threads);
370         } else {
371             map_path = g_strdup_printf(
372                 "/cpus/cpu-map/socket%d/core%d",
373                 num / ms->smp.cores,
374                 num % ms->smp.cores);
375         }
376         qemu_fdt_add_path(ms->fdt, map_path);
377         qemu_fdt_setprop_phandle(ms->fdt, map_path, "cpu", cpu_path);
378 
379         g_free(map_path);
380         g_free(cpu_path);
381     }
382 }
383 
384 static void fdt_add_fw_cfg_node(const LoongArchVirtMachineState *lvms)
385 {
386     char *nodename;
387     hwaddr base = VIRT_FWCFG_BASE;
388     const MachineState *ms = MACHINE(lvms);
389 
390     nodename = g_strdup_printf("/fw_cfg@%" PRIx64, base);
391     qemu_fdt_add_subnode(ms->fdt, nodename);
392     qemu_fdt_setprop_string(ms->fdt, nodename,
393                             "compatible", "qemu,fw-cfg-mmio");
394     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
395                                  2, base, 2, 0x18);
396     qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
397     g_free(nodename);
398 }
399 
400 static void fdt_add_pcie_irq_map_node(const LoongArchVirtMachineState *lvms,
401                                       char *nodename,
402                                       uint32_t *pch_pic_phandle)
403 {
404     int pin, dev;
405     uint32_t irq_map_stride = 0;
406     uint32_t full_irq_map[GPEX_NUM_IRQS *GPEX_NUM_IRQS * 10] = {};
407     uint32_t *irq_map = full_irq_map;
408     const MachineState *ms = MACHINE(lvms);
409 
410     /* This code creates a standard swizzle of interrupts such that
411      * each device's first interrupt is based on it's PCI_SLOT number.
412      * (See pci_swizzle_map_irq_fn())
413      *
414      * We only need one entry per interrupt in the table (not one per
415      * possible slot) seeing the interrupt-map-mask will allow the table
416      * to wrap to any number of devices.
417      */
418 
419     for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
420         int devfn = dev * 0x8;
421 
422         for (pin = 0; pin  < GPEX_NUM_IRQS; pin++) {
423             int irq_nr = 16 + ((pin + PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
424             int i = 0;
425 
426             /* Fill PCI address cells */
427             irq_map[i] = cpu_to_be32(devfn << 8);
428             i += 3;
429 
430             /* Fill PCI Interrupt cells */
431             irq_map[i] = cpu_to_be32(pin + 1);
432             i += 1;
433 
434             /* Fill interrupt controller phandle and cells */
435             irq_map[i++] = cpu_to_be32(*pch_pic_phandle);
436             irq_map[i++] = cpu_to_be32(irq_nr);
437 
438             if (!irq_map_stride) {
439                 irq_map_stride = i;
440             }
441             irq_map += irq_map_stride;
442         }
443     }
444 
445 
446     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-map", full_irq_map,
447                      GPEX_NUM_IRQS * GPEX_NUM_IRQS *
448                      irq_map_stride * sizeof(uint32_t));
449     qemu_fdt_setprop_cells(ms->fdt, nodename, "interrupt-map-mask",
450                      0x1800, 0, 0, 0x7);
451 }
452 
453 static void fdt_add_pcie_node(const LoongArchVirtMachineState *lvms,
454                               uint32_t *pch_pic_phandle,
455                               uint32_t *pch_msi_phandle)
456 {
457     char *nodename;
458     hwaddr base_mmio = VIRT_PCI_MEM_BASE;
459     hwaddr size_mmio = VIRT_PCI_MEM_SIZE;
460     hwaddr base_pio = VIRT_PCI_IO_BASE;
461     hwaddr size_pio = VIRT_PCI_IO_SIZE;
462     hwaddr base_pcie = VIRT_PCI_CFG_BASE;
463     hwaddr size_pcie = VIRT_PCI_CFG_SIZE;
464     hwaddr base = base_pcie;
465 
466     const MachineState *ms = MACHINE(lvms);
467 
468     nodename = g_strdup_printf("/pcie@%" PRIx64, base);
469     qemu_fdt_add_subnode(ms->fdt, nodename);
470     qemu_fdt_setprop_string(ms->fdt, nodename,
471                             "compatible", "pci-host-ecam-generic");
472     qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "pci");
473     qemu_fdt_setprop_cell(ms->fdt, nodename, "#address-cells", 3);
474     qemu_fdt_setprop_cell(ms->fdt, nodename, "#size-cells", 2);
475     qemu_fdt_setprop_cell(ms->fdt, nodename, "linux,pci-domain", 0);
476     qemu_fdt_setprop_cells(ms->fdt, nodename, "bus-range", 0,
477                            PCIE_MMCFG_BUS(VIRT_PCI_CFG_SIZE - 1));
478     qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
479     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
480                                  2, base_pcie, 2, size_pcie);
481     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "ranges",
482                                  1, FDT_PCI_RANGE_IOPORT, 2, VIRT_PCI_IO_OFFSET,
483                                  2, base_pio, 2, size_pio,
484                                  1, FDT_PCI_RANGE_MMIO, 2, base_mmio,
485                                  2, base_mmio, 2, size_mmio);
486     qemu_fdt_setprop_cells(ms->fdt, nodename, "msi-map",
487                            0, *pch_msi_phandle, 0, 0x10000);
488 
489     fdt_add_pcie_irq_map_node(lvms, nodename, pch_pic_phandle);
490 
491     g_free(nodename);
492 }
493 
494 static void fdt_add_memory_node(MachineState *ms,
495                                 uint64_t base, uint64_t size, int node_id)
496 {
497     char *nodename = g_strdup_printf("/memory@%" PRIx64, base);
498 
499     qemu_fdt_add_subnode(ms->fdt, nodename);
500     qemu_fdt_setprop_cells(ms->fdt, nodename, "reg", base >> 32, base,
501                            size >> 32, size);
502     qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "memory");
503 
504     if (ms->numa_state && ms->numa_state->num_nodes) {
505         qemu_fdt_setprop_cell(ms->fdt, nodename, "numa-node-id", node_id);
506     }
507 
508     g_free(nodename);
509 }
510 
511 static void fdt_add_memory_nodes(MachineState *ms)
512 {
513     hwaddr base, size, ram_size, gap;
514     int i, nb_numa_nodes, nodes;
515     NodeInfo *numa_info;
516 
517     ram_size = ms->ram_size;
518     base = VIRT_LOWMEM_BASE;
519     gap = VIRT_LOWMEM_SIZE;
520     nodes = nb_numa_nodes = ms->numa_state->num_nodes;
521     numa_info = ms->numa_state->nodes;
522     if (!nodes) {
523         nodes = 1;
524     }
525 
526     for (i = 0; i < nodes; i++) {
527         if (nb_numa_nodes) {
528             size = numa_info[i].node_mem;
529         } else {
530             size = ram_size;
531         }
532 
533         /*
534          * memory for the node splited into two part
535          *   lowram:  [base, +gap)
536          *   highram: [VIRT_HIGHMEM_BASE, +(len - gap))
537          */
538         if (size >= gap) {
539             fdt_add_memory_node(ms, base, gap, i);
540             size -= gap;
541             base = VIRT_HIGHMEM_BASE;
542             gap = ram_size - VIRT_LOWMEM_SIZE;
543         }
544 
545         if (size) {
546             fdt_add_memory_node(ms, base, size, i);
547             base += size;
548             gap -= size;
549         }
550     }
551 }
552 
553 static void virt_build_smbios(LoongArchVirtMachineState *lvms)
554 {
555     MachineState *ms = MACHINE(lvms);
556     MachineClass *mc = MACHINE_GET_CLASS(lvms);
557     uint8_t *smbios_tables, *smbios_anchor;
558     size_t smbios_tables_len, smbios_anchor_len;
559     const char *product = "QEMU Virtual Machine";
560 
561     if (!lvms->fw_cfg) {
562         return;
563     }
564 
565     smbios_set_defaults("QEMU", product, mc->name);
566 
567     smbios_get_tables(ms, SMBIOS_ENTRY_POINT_TYPE_64,
568                       NULL, 0,
569                       &smbios_tables, &smbios_tables_len,
570                       &smbios_anchor, &smbios_anchor_len, &error_fatal);
571 
572     if (smbios_anchor) {
573         fw_cfg_add_file(lvms->fw_cfg, "etc/smbios/smbios-tables",
574                         smbios_tables, smbios_tables_len);
575         fw_cfg_add_file(lvms->fw_cfg, "etc/smbios/smbios-anchor",
576                         smbios_anchor, smbios_anchor_len);
577     }
578 }
579 
580 static void virt_done(Notifier *notifier, void *data)
581 {
582     LoongArchVirtMachineState *lvms = container_of(notifier,
583                                       LoongArchVirtMachineState, machine_done);
584     virt_build_smbios(lvms);
585     loongarch_acpi_setup(lvms);
586 }
587 
588 static void virt_powerdown_req(Notifier *notifier, void *opaque)
589 {
590     LoongArchVirtMachineState *s;
591 
592     s = container_of(notifier, LoongArchVirtMachineState, powerdown_notifier);
593     acpi_send_event(s->acpi_ged, ACPI_POWER_DOWN_STATUS);
594 }
595 
596 static void memmap_add_entry(uint64_t address, uint64_t length, uint32_t type)
597 {
598     /* Ensure there are no duplicate entries. */
599     for (unsigned i = 0; i < memmap_entries; i++) {
600         assert(memmap_table[i].address != address);
601     }
602 
603     memmap_table = g_renew(struct memmap_entry, memmap_table,
604                            memmap_entries + 1);
605     memmap_table[memmap_entries].address = cpu_to_le64(address);
606     memmap_table[memmap_entries].length = cpu_to_le64(length);
607     memmap_table[memmap_entries].type = cpu_to_le32(type);
608     memmap_table[memmap_entries].reserved = 0;
609     memmap_entries++;
610 }
611 
612 static DeviceState *create_acpi_ged(DeviceState *pch_pic,
613                                     LoongArchVirtMachineState *lvms)
614 {
615     DeviceState *dev;
616     MachineState *ms = MACHINE(lvms);
617     uint32_t event = ACPI_GED_PWR_DOWN_EVT;
618 
619     if (ms->ram_slots) {
620         event |= ACPI_GED_MEM_HOTPLUG_EVT;
621     }
622     dev = qdev_new(TYPE_ACPI_GED);
623     qdev_prop_set_uint32(dev, "ged-event", event);
624     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
625 
626     /* ged event */
627     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, VIRT_GED_EVT_ADDR);
628     /* memory hotplug */
629     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 1, VIRT_GED_MEM_ADDR);
630     /* ged regs used for reset and power down */
631     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, VIRT_GED_REG_ADDR);
632 
633     sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0,
634                        qdev_get_gpio_in(pch_pic, VIRT_SCI_IRQ - VIRT_GSI_BASE));
635     return dev;
636 }
637 
638 static DeviceState *create_platform_bus(DeviceState *pch_pic)
639 {
640     DeviceState *dev;
641     SysBusDevice *sysbus;
642     int i, irq;
643     MemoryRegion *sysmem = get_system_memory();
644 
645     dev = qdev_new(TYPE_PLATFORM_BUS_DEVICE);
646     dev->id = g_strdup(TYPE_PLATFORM_BUS_DEVICE);
647     qdev_prop_set_uint32(dev, "num_irqs", VIRT_PLATFORM_BUS_NUM_IRQS);
648     qdev_prop_set_uint32(dev, "mmio_size", VIRT_PLATFORM_BUS_SIZE);
649     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
650 
651     sysbus = SYS_BUS_DEVICE(dev);
652     for (i = 0; i < VIRT_PLATFORM_BUS_NUM_IRQS; i++) {
653         irq = VIRT_PLATFORM_BUS_IRQ - VIRT_GSI_BASE + i;
654         sysbus_connect_irq(sysbus, i, qdev_get_gpio_in(pch_pic, irq));
655     }
656 
657     memory_region_add_subregion(sysmem,
658                                 VIRT_PLATFORM_BUS_BASEADDRESS,
659                                 sysbus_mmio_get_region(sysbus, 0));
660     return dev;
661 }
662 
663 static void virt_devices_init(DeviceState *pch_pic,
664                                    LoongArchVirtMachineState *lvms,
665                                    uint32_t *pch_pic_phandle,
666                                    uint32_t *pch_msi_phandle)
667 {
668     MachineClass *mc = MACHINE_GET_CLASS(lvms);
669     DeviceState *gpex_dev;
670     SysBusDevice *d;
671     PCIBus *pci_bus;
672     MemoryRegion *ecam_alias, *ecam_reg, *pio_alias, *pio_reg;
673     MemoryRegion *mmio_alias, *mmio_reg;
674     int i;
675 
676     gpex_dev = qdev_new(TYPE_GPEX_HOST);
677     d = SYS_BUS_DEVICE(gpex_dev);
678     sysbus_realize_and_unref(d, &error_fatal);
679     pci_bus = PCI_HOST_BRIDGE(gpex_dev)->bus;
680     lvms->pci_bus = pci_bus;
681 
682     /* Map only part size_ecam bytes of ECAM space */
683     ecam_alias = g_new0(MemoryRegion, 1);
684     ecam_reg = sysbus_mmio_get_region(d, 0);
685     memory_region_init_alias(ecam_alias, OBJECT(gpex_dev), "pcie-ecam",
686                              ecam_reg, 0, VIRT_PCI_CFG_SIZE);
687     memory_region_add_subregion(get_system_memory(), VIRT_PCI_CFG_BASE,
688                                 ecam_alias);
689 
690     /* Map PCI mem space */
691     mmio_alias = g_new0(MemoryRegion, 1);
692     mmio_reg = sysbus_mmio_get_region(d, 1);
693     memory_region_init_alias(mmio_alias, OBJECT(gpex_dev), "pcie-mmio",
694                              mmio_reg, VIRT_PCI_MEM_BASE, VIRT_PCI_MEM_SIZE);
695     memory_region_add_subregion(get_system_memory(), VIRT_PCI_MEM_BASE,
696                                 mmio_alias);
697 
698     /* Map PCI IO port space. */
699     pio_alias = g_new0(MemoryRegion, 1);
700     pio_reg = sysbus_mmio_get_region(d, 2);
701     memory_region_init_alias(pio_alias, OBJECT(gpex_dev), "pcie-io", pio_reg,
702                              VIRT_PCI_IO_OFFSET, VIRT_PCI_IO_SIZE);
703     memory_region_add_subregion(get_system_memory(), VIRT_PCI_IO_BASE,
704                                 pio_alias);
705 
706     for (i = 0; i < GPEX_NUM_IRQS; i++) {
707         sysbus_connect_irq(d, i,
708                            qdev_get_gpio_in(pch_pic, 16 + i));
709         gpex_set_irq_num(GPEX_HOST(gpex_dev), i, 16 + i);
710     }
711 
712     /* Add pcie node */
713     fdt_add_pcie_node(lvms, pch_pic_phandle, pch_msi_phandle);
714 
715     /*
716      * Create uart fdt node in reverse order so that they appear
717      * in the finished device tree lowest address first
718      */
719     for (i = VIRT_UART_COUNT; i --> 0;) {
720         hwaddr base = VIRT_UART_BASE + i * VIRT_UART_SIZE;
721         int irq = VIRT_UART_IRQ + i - VIRT_GSI_BASE;
722         serial_mm_init(get_system_memory(), base, 0,
723                        qdev_get_gpio_in(pch_pic, irq),
724                        115200, serial_hd(i), DEVICE_LITTLE_ENDIAN);
725         fdt_add_uart_node(lvms, pch_pic_phandle, base, irq, i == 0);
726     }
727 
728     /* Network init */
729     pci_init_nic_devices(pci_bus, mc->default_nic);
730 
731     /*
732      * There are some invalid guest memory access.
733      * Create some unimplemented devices to emulate this.
734      */
735     create_unimplemented_device("pci-dma-cfg", 0x1001041c, 0x4);
736     sysbus_create_simple("ls7a_rtc", VIRT_RTC_REG_BASE,
737                          qdev_get_gpio_in(pch_pic,
738                          VIRT_RTC_IRQ - VIRT_GSI_BASE));
739     fdt_add_rtc_node(lvms, pch_pic_phandle);
740 
741     /* acpi ged */
742     lvms->acpi_ged = create_acpi_ged(pch_pic, lvms);
743     /* platform bus */
744     lvms->platform_bus_dev = create_platform_bus(pch_pic);
745 }
746 
747 static void virt_irq_init(LoongArchVirtMachineState *lvms)
748 {
749     MachineState *ms = MACHINE(lvms);
750     DeviceState *pch_pic, *pch_msi, *cpudev;
751     DeviceState *ipi, *extioi;
752     SysBusDevice *d;
753     LoongArchCPU *lacpu;
754     CPULoongArchState *env;
755     CPUState *cpu_state;
756     int cpu, pin, i, start, num;
757     uint32_t cpuintc_phandle, eiointc_phandle, pch_pic_phandle, pch_msi_phandle;
758 
759     /*
760      * Extended IRQ model.
761      *                                 |
762      * +-----------+     +-------------|--------+     +-----------+
763      * | IPI/Timer | --> | CPUINTC(0-3)|(4-255) | <-- | IPI/Timer |
764      * +-----------+     +-------------|--------+     +-----------+
765      *                         ^       |
766      *                         |
767      *                    +---------+
768      *                    | EIOINTC |
769      *                    +---------+
770      *                     ^       ^
771      *                     |       |
772      *              +---------+ +---------+
773      *              | PCH-PIC | | PCH-MSI |
774      *              +---------+ +---------+
775      *                ^      ^          ^
776      *                |      |          |
777      *         +--------+ +---------+ +---------+
778      *         | UARTs  | | Devices | | Devices |
779      *         +--------+ +---------+ +---------+
780      *
781      * Virt extended IRQ model.
782      *
783      *   +-----+    +---------------+     +-------+
784      *   | IPI |--> | CPUINTC(0-255)| <-- | Timer |
785      *   +-----+    +---------------+     +-------+
786      *                     ^
787      *                     |
788      *               +-----------+
789      *               | V-EIOINTC |
790      *               +-----------+
791      *                ^         ^
792      *                |         |
793      *         +---------+ +---------+
794      *         | PCH-PIC | | PCH-MSI |
795      *         +---------+ +---------+
796      *           ^      ^          ^
797      *           |      |          |
798      *    +--------+ +---------+ +---------+
799      *    | UARTs  | | Devices | | Devices |
800      *    +--------+ +---------+ +---------+
801      */
802 
803     /* Create IPI device */
804     ipi = qdev_new(TYPE_LOONGARCH_IPI);
805     qdev_prop_set_uint32(ipi, "num-cpu", ms->smp.cpus);
806     sysbus_realize_and_unref(SYS_BUS_DEVICE(ipi), &error_fatal);
807 
808     /* IPI iocsr memory region */
809     memory_region_add_subregion(&lvms->system_iocsr, SMP_IPI_MAILBOX,
810                    sysbus_mmio_get_region(SYS_BUS_DEVICE(ipi), 0));
811     memory_region_add_subregion(&lvms->system_iocsr, MAIL_SEND_ADDR,
812                    sysbus_mmio_get_region(SYS_BUS_DEVICE(ipi), 1));
813 
814     /* Add cpu interrupt-controller */
815     fdt_add_cpuic_node(lvms, &cpuintc_phandle);
816 
817     for (cpu = 0; cpu < ms->smp.cpus; cpu++) {
818         cpu_state = qemu_get_cpu(cpu);
819         cpudev = DEVICE(cpu_state);
820         lacpu = LOONGARCH_CPU(cpu_state);
821         env = &(lacpu->env);
822         env->address_space_iocsr = &lvms->as_iocsr;
823 
824         /* connect ipi irq to cpu irq */
825         qdev_connect_gpio_out(ipi, cpu, qdev_get_gpio_in(cpudev, IRQ_IPI));
826         env->ipistate = ipi;
827     }
828 
829     /* Create EXTIOI device */
830     extioi = qdev_new(TYPE_LOONGARCH_EXTIOI);
831     qdev_prop_set_uint32(extioi, "num-cpu", ms->smp.cpus);
832     if (virt_is_veiointc_enabled(lvms)) {
833         qdev_prop_set_bit(extioi, "has-virtualization-extension", true);
834     }
835     sysbus_realize_and_unref(SYS_BUS_DEVICE(extioi), &error_fatal);
836     memory_region_add_subregion(&lvms->system_iocsr, APIC_BASE,
837                     sysbus_mmio_get_region(SYS_BUS_DEVICE(extioi), 0));
838     if (virt_is_veiointc_enabled(lvms)) {
839         memory_region_add_subregion(&lvms->system_iocsr, EXTIOI_VIRT_BASE,
840                     sysbus_mmio_get_region(SYS_BUS_DEVICE(extioi), 1));
841     }
842 
843     /*
844      * connect ext irq to the cpu irq
845      * cpu_pin[9:2] <= intc_pin[7:0]
846      */
847     for (cpu = 0; cpu < ms->smp.cpus; cpu++) {
848         cpudev = DEVICE(qemu_get_cpu(cpu));
849         for (pin = 0; pin < LS3A_INTC_IP; pin++) {
850             qdev_connect_gpio_out(extioi, (cpu * 8 + pin),
851                                   qdev_get_gpio_in(cpudev, pin + 2));
852         }
853     }
854 
855     /* Add Extend I/O Interrupt Controller node */
856     fdt_add_eiointc_node(lvms, &cpuintc_phandle, &eiointc_phandle);
857 
858     pch_pic = qdev_new(TYPE_LOONGARCH_PCH_PIC);
859     num = VIRT_PCH_PIC_IRQ_NUM;
860     qdev_prop_set_uint32(pch_pic, "pch_pic_irq_num", num);
861     d = SYS_BUS_DEVICE(pch_pic);
862     sysbus_realize_and_unref(d, &error_fatal);
863     memory_region_add_subregion(get_system_memory(), VIRT_IOAPIC_REG_BASE,
864                             sysbus_mmio_get_region(d, 0));
865     memory_region_add_subregion(get_system_memory(),
866                             VIRT_IOAPIC_REG_BASE + PCH_PIC_ROUTE_ENTRY_OFFSET,
867                             sysbus_mmio_get_region(d, 1));
868     memory_region_add_subregion(get_system_memory(),
869                             VIRT_IOAPIC_REG_BASE + PCH_PIC_INT_STATUS_LO,
870                             sysbus_mmio_get_region(d, 2));
871 
872     /* Connect pch_pic irqs to extioi */
873     for (i = 0; i < num; i++) {
874         qdev_connect_gpio_out(DEVICE(d), i, qdev_get_gpio_in(extioi, i));
875     }
876 
877     /* Add PCH PIC node */
878     fdt_add_pch_pic_node(lvms, &eiointc_phandle, &pch_pic_phandle);
879 
880     pch_msi = qdev_new(TYPE_LOONGARCH_PCH_MSI);
881     start   =  num;
882     num = EXTIOI_IRQS - start;
883     qdev_prop_set_uint32(pch_msi, "msi_irq_base", start);
884     qdev_prop_set_uint32(pch_msi, "msi_irq_num", num);
885     d = SYS_BUS_DEVICE(pch_msi);
886     sysbus_realize_and_unref(d, &error_fatal);
887     sysbus_mmio_map(d, 0, VIRT_PCH_MSI_ADDR_LOW);
888     for (i = 0; i < num; i++) {
889         /* Connect pch_msi irqs to extioi */
890         qdev_connect_gpio_out(DEVICE(d), i,
891                               qdev_get_gpio_in(extioi, i + start));
892     }
893 
894     /* Add PCH MSI node */
895     fdt_add_pch_msi_node(lvms, &eiointc_phandle, &pch_msi_phandle);
896 
897     virt_devices_init(pch_pic, lvms, &pch_pic_phandle, &pch_msi_phandle);
898 }
899 
900 static void virt_firmware_init(LoongArchVirtMachineState *lvms)
901 {
902     char *filename = MACHINE(lvms)->firmware;
903     char *bios_name = NULL;
904     int bios_size, i;
905     BlockBackend *pflash_blk0;
906     MemoryRegion *mr;
907 
908     lvms->bios_loaded = false;
909 
910     /* Map legacy -drive if=pflash to machine properties */
911     for (i = 0; i < ARRAY_SIZE(lvms->flash); i++) {
912         pflash_cfi01_legacy_drive(lvms->flash[i],
913                                   drive_get(IF_PFLASH, 0, i));
914     }
915 
916     virt_flash_map(lvms, get_system_memory());
917 
918     pflash_blk0 = pflash_cfi01_get_blk(lvms->flash[0]);
919 
920     if (pflash_blk0) {
921         if (filename) {
922             error_report("cannot use both '-bios' and '-drive if=pflash'"
923                          "options at once");
924             exit(1);
925         }
926         lvms->bios_loaded = true;
927         return;
928     }
929 
930     if (filename) {
931         bios_name = qemu_find_file(QEMU_FILE_TYPE_BIOS, filename);
932         if (!bios_name) {
933             error_report("Could not find ROM image '%s'", filename);
934             exit(1);
935         }
936 
937         mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(lvms->flash[0]), 0);
938         bios_size = load_image_mr(bios_name, mr);
939         if (bios_size < 0) {
940             error_report("Could not load ROM image '%s'", bios_name);
941             exit(1);
942         }
943         g_free(bios_name);
944         lvms->bios_loaded = true;
945     }
946 }
947 
948 static MemTxResult virt_iocsr_misc_write(void *opaque, hwaddr addr,
949                                          uint64_t val, unsigned size,
950                                          MemTxAttrs attrs)
951 {
952     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(opaque);
953     uint64_t features;
954 
955     switch (addr) {
956     case MISC_FUNC_REG:
957         if (!virt_is_veiointc_enabled(lvms)) {
958             return MEMTX_OK;
959         }
960 
961         features = address_space_ldl(&lvms->as_iocsr,
962                                      EXTIOI_VIRT_BASE + EXTIOI_VIRT_CONFIG,
963                                      attrs, NULL);
964         if (val & BIT_ULL(IOCSRM_EXTIOI_EN)) {
965             features |= BIT(EXTIOI_ENABLE);
966         }
967         if (val & BIT_ULL(IOCSRM_EXTIOI_INT_ENCODE)) {
968             features |= BIT(EXTIOI_ENABLE_INT_ENCODE);
969         }
970 
971         address_space_stl(&lvms->as_iocsr,
972                           EXTIOI_VIRT_BASE + EXTIOI_VIRT_CONFIG,
973                           features, attrs, NULL);
974         break;
975     default:
976         g_assert_not_reached();
977     }
978 
979     return MEMTX_OK;
980 }
981 
982 static MemTxResult virt_iocsr_misc_read(void *opaque, hwaddr addr,
983                                         uint64_t *data,
984                                         unsigned size, MemTxAttrs attrs)
985 {
986     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(opaque);
987     uint64_t ret = 0;
988     int features;
989 
990     switch (addr) {
991     case VERSION_REG:
992         ret = 0x11ULL;
993         break;
994     case FEATURE_REG:
995         ret = BIT(IOCSRF_MSI) | BIT(IOCSRF_EXTIOI) | BIT(IOCSRF_CSRIPI);
996         if (kvm_enabled()) {
997             ret |= BIT(IOCSRF_VM);
998         }
999         break;
1000     case VENDOR_REG:
1001         ret = 0x6e6f73676e6f6f4cULL; /* "Loongson" */
1002         break;
1003     case CPUNAME_REG:
1004         ret = 0x303030354133ULL;     /* "3A5000" */
1005         break;
1006     case MISC_FUNC_REG:
1007         if (!virt_is_veiointc_enabled(lvms)) {
1008             ret |= BIT_ULL(IOCSRM_EXTIOI_EN);
1009             break;
1010         }
1011 
1012         features = address_space_ldl(&lvms->as_iocsr,
1013                                      EXTIOI_VIRT_BASE + EXTIOI_VIRT_CONFIG,
1014                                      attrs, NULL);
1015         if (features & BIT(EXTIOI_ENABLE)) {
1016             ret |= BIT_ULL(IOCSRM_EXTIOI_EN);
1017         }
1018         if (features & BIT(EXTIOI_ENABLE_INT_ENCODE)) {
1019             ret |= BIT_ULL(IOCSRM_EXTIOI_INT_ENCODE);
1020         }
1021         break;
1022     default:
1023         g_assert_not_reached();
1024     }
1025 
1026     *data = ret;
1027     return MEMTX_OK;
1028 }
1029 
1030 static const MemoryRegionOps virt_iocsr_misc_ops = {
1031     .read_with_attrs  = virt_iocsr_misc_read,
1032     .write_with_attrs = virt_iocsr_misc_write,
1033     .endianness = DEVICE_LITTLE_ENDIAN,
1034     .valid = {
1035         .min_access_size = 4,
1036         .max_access_size = 8,
1037     },
1038     .impl = {
1039         .min_access_size = 8,
1040         .max_access_size = 8,
1041     },
1042 };
1043 
1044 static void fw_cfg_add_memory(MachineState *ms)
1045 {
1046     hwaddr base, size, ram_size, gap;
1047     int nb_numa_nodes, nodes;
1048     NodeInfo *numa_info;
1049 
1050     ram_size = ms->ram_size;
1051     base = VIRT_LOWMEM_BASE;
1052     gap = VIRT_LOWMEM_SIZE;
1053     nodes = nb_numa_nodes = ms->numa_state->num_nodes;
1054     numa_info = ms->numa_state->nodes;
1055     if (!nodes) {
1056         nodes = 1;
1057     }
1058 
1059     /* add fw_cfg memory map of node0 */
1060     if (nb_numa_nodes) {
1061         size = numa_info[0].node_mem;
1062     } else {
1063         size = ram_size;
1064     }
1065 
1066     if (size >= gap) {
1067         memmap_add_entry(base, gap, 1);
1068         size -= gap;
1069         base = VIRT_HIGHMEM_BASE;
1070     }
1071 
1072     if (size) {
1073         memmap_add_entry(base, size, 1);
1074         base += size;
1075     }
1076 
1077     if (nodes < 2) {
1078         return;
1079     }
1080 
1081     /* add fw_cfg memory map of other nodes */
1082     if (numa_info[0].node_mem < gap && ram_size > gap) {
1083         /*
1084          * memory map for the maining nodes splited into two part
1085          * lowram:  [base, +(gap - numa_info[0].node_mem))
1086          * highram: [VIRT_HIGHMEM_BASE, +(ram_size - gap))
1087          */
1088         memmap_add_entry(base, gap - numa_info[0].node_mem, 1);
1089         size = ram_size - gap;
1090         base = VIRT_HIGHMEM_BASE;
1091     } else {
1092         size = ram_size - numa_info[0].node_mem;
1093     }
1094 
1095    if (size)
1096         memmap_add_entry(base, size, 1);
1097 }
1098 
1099 static void virt_init(MachineState *machine)
1100 {
1101     LoongArchCPU *lacpu;
1102     const char *cpu_model = machine->cpu_type;
1103     MemoryRegion *address_space_mem = get_system_memory();
1104     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(machine);
1105     int i;
1106     hwaddr base, size, ram_size = machine->ram_size;
1107     const CPUArchIdList *possible_cpus;
1108     MachineClass *mc = MACHINE_GET_CLASS(machine);
1109     CPUState *cpu;
1110 
1111     if (!cpu_model) {
1112         cpu_model = LOONGARCH_CPU_TYPE_NAME("la464");
1113     }
1114 
1115     create_fdt(lvms);
1116 
1117     /* Create IOCSR space */
1118     memory_region_init_io(&lvms->system_iocsr, OBJECT(machine), NULL,
1119                           machine, "iocsr", UINT64_MAX);
1120     address_space_init(&lvms->as_iocsr, &lvms->system_iocsr, "IOCSR");
1121     memory_region_init_io(&lvms->iocsr_mem, OBJECT(machine),
1122                           &virt_iocsr_misc_ops,
1123                           machine, "iocsr_misc", 0x428);
1124     memory_region_add_subregion(&lvms->system_iocsr, 0, &lvms->iocsr_mem);
1125 
1126     /* Init CPUs */
1127     possible_cpus = mc->possible_cpu_arch_ids(machine);
1128     for (i = 0; i < possible_cpus->len; i++) {
1129         cpu = cpu_create(machine->cpu_type);
1130         cpu->cpu_index = i;
1131         machine->possible_cpus->cpus[i].cpu = cpu;
1132         lacpu = LOONGARCH_CPU(cpu);
1133         lacpu->phy_id = machine->possible_cpus->cpus[i].arch_id;
1134     }
1135     fdt_add_cpu_nodes(lvms);
1136     fdt_add_memory_nodes(machine);
1137     fw_cfg_add_memory(machine);
1138 
1139     /* Node0 memory */
1140     size = ram_size;
1141     base = VIRT_LOWMEM_BASE;
1142     if (size > VIRT_LOWMEM_SIZE) {
1143         size = VIRT_LOWMEM_SIZE;
1144     }
1145 
1146     memory_region_init_alias(&lvms->lowmem, NULL, "loongarch.lowram",
1147                               machine->ram, base, size);
1148     memory_region_add_subregion(address_space_mem, base, &lvms->lowmem);
1149     base += size;
1150     if (ram_size - size) {
1151         base = VIRT_HIGHMEM_BASE;
1152         memory_region_init_alias(&lvms->highmem, NULL, "loongarch.highram",
1153                 machine->ram, VIRT_LOWMEM_BASE + size, ram_size - size);
1154         memory_region_add_subregion(address_space_mem, base, &lvms->highmem);
1155         base += ram_size - size;
1156     }
1157 
1158     /* initialize device memory address space */
1159     if (machine->ram_size < machine->maxram_size) {
1160         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
1161 
1162         if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {
1163             error_report("unsupported amount of memory slots: %"PRIu64,
1164                          machine->ram_slots);
1165             exit(EXIT_FAILURE);
1166         }
1167 
1168         if (QEMU_ALIGN_UP(machine->maxram_size,
1169                           TARGET_PAGE_SIZE) != machine->maxram_size) {
1170             error_report("maximum memory size must by aligned to multiple of "
1171                          "%d bytes", TARGET_PAGE_SIZE);
1172             exit(EXIT_FAILURE);
1173         }
1174         machine_memory_devices_init(machine, base, device_mem_size);
1175     }
1176 
1177     /* load the BIOS image. */
1178     virt_firmware_init(lvms);
1179 
1180     /* fw_cfg init */
1181     lvms->fw_cfg = virt_fw_cfg_init(ram_size, machine);
1182     rom_set_fw(lvms->fw_cfg);
1183     if (lvms->fw_cfg != NULL) {
1184         fw_cfg_add_file(lvms->fw_cfg, "etc/memmap",
1185                         memmap_table,
1186                         sizeof(struct memmap_entry) * (memmap_entries));
1187     }
1188     fdt_add_fw_cfg_node(lvms);
1189     fdt_add_flash_node(lvms);
1190 
1191     /* Initialize the IO interrupt subsystem */
1192     virt_irq_init(lvms);
1193     platform_bus_add_all_fdt_nodes(machine->fdt, "/platic",
1194                                    VIRT_PLATFORM_BUS_BASEADDRESS,
1195                                    VIRT_PLATFORM_BUS_SIZE,
1196                                    VIRT_PLATFORM_BUS_IRQ);
1197     lvms->machine_done.notify = virt_done;
1198     qemu_add_machine_init_done_notifier(&lvms->machine_done);
1199      /* connect powerdown request */
1200     lvms->powerdown_notifier.notify = virt_powerdown_req;
1201     qemu_register_powerdown_notifier(&lvms->powerdown_notifier);
1202 
1203     /*
1204      * Since lowmem region starts from 0 and Linux kernel legacy start address
1205      * at 2 MiB, FDT base address is located at 1 MiB to avoid NULL pointer
1206      * access. FDT size limit with 1 MiB.
1207      * Put the FDT into the memory map as a ROM image: this will ensure
1208      * the FDT is copied again upon reset, even if addr points into RAM.
1209      */
1210     qemu_fdt_dumpdtb(machine->fdt, lvms->fdt_size);
1211     rom_add_blob_fixed_as("fdt", machine->fdt, lvms->fdt_size, FDT_BASE,
1212                           &address_space_memory);
1213     qemu_register_reset_nosnapshotload(qemu_fdt_randomize_seeds,
1214             rom_ptr_for_as(&address_space_memory, FDT_BASE, lvms->fdt_size));
1215 
1216     lvms->bootinfo.ram_size = ram_size;
1217     loongarch_load_kernel(machine, &lvms->bootinfo);
1218 }
1219 
1220 static void virt_get_acpi(Object *obj, Visitor *v, const char *name,
1221                           void *opaque, Error **errp)
1222 {
1223     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(obj);
1224     OnOffAuto acpi = lvms->acpi;
1225 
1226     visit_type_OnOffAuto(v, name, &acpi, errp);
1227 }
1228 
1229 static void virt_set_acpi(Object *obj, Visitor *v, const char *name,
1230                                void *opaque, Error **errp)
1231 {
1232     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(obj);
1233 
1234     visit_type_OnOffAuto(v, name, &lvms->acpi, errp);
1235 }
1236 
1237 static void virt_initfn(Object *obj)
1238 {
1239     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(obj);
1240 
1241     if (tcg_enabled()) {
1242         lvms->veiointc = ON_OFF_AUTO_OFF;
1243     }
1244     lvms->acpi = ON_OFF_AUTO_AUTO;
1245     lvms->oem_id = g_strndup(ACPI_BUILD_APPNAME6, 6);
1246     lvms->oem_table_id = g_strndup(ACPI_BUILD_APPNAME8, 8);
1247     virt_flash_create(lvms);
1248 }
1249 
1250 static bool memhp_type_supported(DeviceState *dev)
1251 {
1252     /* we only support pc dimm now */
1253     return object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) &&
1254            !object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
1255 }
1256 
1257 static void virt_mem_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
1258                                  Error **errp)
1259 {
1260     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev), errp);
1261 }
1262 
1263 static void virt_device_pre_plug(HotplugHandler *hotplug_dev,
1264                                             DeviceState *dev, Error **errp)
1265 {
1266     if (memhp_type_supported(dev)) {
1267         virt_mem_pre_plug(hotplug_dev, dev, errp);
1268     }
1269 }
1270 
1271 static void virt_mem_unplug_request(HotplugHandler *hotplug_dev,
1272                                      DeviceState *dev, Error **errp)
1273 {
1274     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(hotplug_dev);
1275 
1276     /* the acpi ged is always exist */
1277     hotplug_handler_unplug_request(HOTPLUG_HANDLER(lvms->acpi_ged), dev,
1278                                    errp);
1279 }
1280 
1281 static void virt_device_unplug_request(HotplugHandler *hotplug_dev,
1282                                           DeviceState *dev, Error **errp)
1283 {
1284     if (memhp_type_supported(dev)) {
1285         virt_mem_unplug_request(hotplug_dev, dev, errp);
1286     }
1287 }
1288 
1289 static void virt_mem_unplug(HotplugHandler *hotplug_dev,
1290                              DeviceState *dev, Error **errp)
1291 {
1292     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(hotplug_dev);
1293 
1294     hotplug_handler_unplug(HOTPLUG_HANDLER(lvms->acpi_ged), dev, errp);
1295     pc_dimm_unplug(PC_DIMM(dev), MACHINE(lvms));
1296     qdev_unrealize(dev);
1297 }
1298 
1299 static void virt_device_unplug(HotplugHandler *hotplug_dev,
1300                                           DeviceState *dev, Error **errp)
1301 {
1302     if (memhp_type_supported(dev)) {
1303         virt_mem_unplug(hotplug_dev, dev, errp);
1304     }
1305 }
1306 
1307 static void virt_mem_plug(HotplugHandler *hotplug_dev,
1308                              DeviceState *dev, Error **errp)
1309 {
1310     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(hotplug_dev);
1311 
1312     pc_dimm_plug(PC_DIMM(dev), MACHINE(lvms));
1313     hotplug_handler_plug(HOTPLUG_HANDLER(lvms->acpi_ged),
1314                          dev, &error_abort);
1315 }
1316 
1317 static void virt_device_plug_cb(HotplugHandler *hotplug_dev,
1318                                         DeviceState *dev, Error **errp)
1319 {
1320     LoongArchVirtMachineState *lvms = LOONGARCH_VIRT_MACHINE(hotplug_dev);
1321     MachineClass *mc = MACHINE_GET_CLASS(lvms);
1322     PlatformBusDevice *pbus;
1323 
1324     if (device_is_dynamic_sysbus(mc, dev)) {
1325         if (lvms->platform_bus_dev) {
1326             pbus = PLATFORM_BUS_DEVICE(lvms->platform_bus_dev);
1327             platform_bus_link_device(pbus, SYS_BUS_DEVICE(dev));
1328         }
1329     } else if (memhp_type_supported(dev)) {
1330         virt_mem_plug(hotplug_dev, dev, errp);
1331     }
1332 }
1333 
1334 static HotplugHandler *virt_get_hotplug_handler(MachineState *machine,
1335                                                 DeviceState *dev)
1336 {
1337     MachineClass *mc = MACHINE_GET_CLASS(machine);
1338 
1339     if (device_is_dynamic_sysbus(mc, dev) ||
1340         object_dynamic_cast(OBJECT(dev), TYPE_VIRTIO_IOMMU_PCI) ||
1341         memhp_type_supported(dev)) {
1342         return HOTPLUG_HANDLER(machine);
1343     }
1344     return NULL;
1345 }
1346 
1347 static const CPUArchIdList *virt_possible_cpu_arch_ids(MachineState *ms)
1348 {
1349     int n;
1350     unsigned int max_cpus = ms->smp.max_cpus;
1351 
1352     if (ms->possible_cpus) {
1353         assert(ms->possible_cpus->len == max_cpus);
1354         return ms->possible_cpus;
1355     }
1356 
1357     ms->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
1358                                   sizeof(CPUArchId) * max_cpus);
1359     ms->possible_cpus->len = max_cpus;
1360     for (n = 0; n < ms->possible_cpus->len; n++) {
1361         ms->possible_cpus->cpus[n].type = ms->cpu_type;
1362         ms->possible_cpus->cpus[n].arch_id = n;
1363 
1364         ms->possible_cpus->cpus[n].props.has_socket_id = true;
1365         ms->possible_cpus->cpus[n].props.socket_id  =
1366                                    n / (ms->smp.cores * ms->smp.threads);
1367         ms->possible_cpus->cpus[n].props.has_core_id = true;
1368         ms->possible_cpus->cpus[n].props.core_id =
1369                                    n / ms->smp.threads % ms->smp.cores;
1370         ms->possible_cpus->cpus[n].props.has_thread_id = true;
1371         ms->possible_cpus->cpus[n].props.thread_id = n % ms->smp.threads;
1372     }
1373     return ms->possible_cpus;
1374 }
1375 
1376 static CpuInstanceProperties virt_cpu_index_to_props(MachineState *ms,
1377                                                      unsigned cpu_index)
1378 {
1379     MachineClass *mc = MACHINE_GET_CLASS(ms);
1380     const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(ms);
1381 
1382     assert(cpu_index < possible_cpus->len);
1383     return possible_cpus->cpus[cpu_index].props;
1384 }
1385 
1386 static int64_t virt_get_default_cpu_node_id(const MachineState *ms, int idx)
1387 {
1388     int64_t socket_id;
1389 
1390     if (ms->numa_state->num_nodes) {
1391         socket_id = ms->possible_cpus->cpus[idx].props.socket_id;
1392         return socket_id % ms->numa_state->num_nodes;
1393     } else {
1394         return 0;
1395     }
1396 }
1397 
1398 static void virt_class_init(ObjectClass *oc, void *data)
1399 {
1400     MachineClass *mc = MACHINE_CLASS(oc);
1401     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
1402 
1403     mc->init = virt_init;
1404     mc->default_cpu_type = LOONGARCH_CPU_TYPE_NAME("la464");
1405     mc->default_ram_id = "loongarch.ram";
1406     mc->desc = "QEMU LoongArch Virtual Machine";
1407     mc->max_cpus = LOONGARCH_MAX_CPUS;
1408     mc->is_default = 1;
1409     mc->default_kernel_irqchip_split = false;
1410     mc->block_default_type = IF_VIRTIO;
1411     mc->default_boot_order = "c";
1412     mc->no_cdrom = 1;
1413     mc->possible_cpu_arch_ids = virt_possible_cpu_arch_ids;
1414     mc->cpu_index_to_instance_props = virt_cpu_index_to_props;
1415     mc->get_default_cpu_node_id = virt_get_default_cpu_node_id;
1416     mc->numa_mem_supported = true;
1417     mc->auto_enable_numa_with_memhp = true;
1418     mc->auto_enable_numa_with_memdev = true;
1419     mc->get_hotplug_handler = virt_get_hotplug_handler;
1420     mc->default_nic = "virtio-net-pci";
1421     hc->plug = virt_device_plug_cb;
1422     hc->pre_plug = virt_device_pre_plug;
1423     hc->unplug_request = virt_device_unplug_request;
1424     hc->unplug = virt_device_unplug;
1425 
1426     object_class_property_add(oc, "acpi", "OnOffAuto",
1427         virt_get_acpi, virt_set_acpi,
1428         NULL, NULL);
1429     object_class_property_set_description(oc, "acpi",
1430         "Enable ACPI");
1431     object_class_property_add(oc, "v-eiointc", "OnOffAuto",
1432         virt_get_veiointc, virt_set_veiointc,
1433         NULL, NULL);
1434     object_class_property_set_description(oc, "v-eiointc",
1435                             "Enable Virt Extend I/O Interrupt Controller.");
1436     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_RAMFB_DEVICE);
1437 #ifdef CONFIG_TPM
1438     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
1439 #endif
1440 }
1441 
1442 static const TypeInfo virt_machine_types[] = {
1443     {
1444         .name           = TYPE_LOONGARCH_VIRT_MACHINE,
1445         .parent         = TYPE_MACHINE,
1446         .instance_size  = sizeof(LoongArchVirtMachineState),
1447         .class_init     = virt_class_init,
1448         .instance_init  = virt_initfn,
1449         .interfaces = (InterfaceInfo[]) {
1450          { TYPE_HOTPLUG_HANDLER },
1451          { }
1452         },
1453     }
1454 };
1455 
1456 DEFINE_TYPES(virt_machine_types)
1457