xref: /openbmc/qemu/hw/loongarch/virt.c (revision 78f314cf)
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.h"
13 #include "sysemu/sysemu.h"
14 #include "sysemu/qtest.h"
15 #include "sysemu/runstate.h"
16 #include "sysemu/reset.h"
17 #include "sysemu/rtc.h"
18 #include "hw/loongarch/virt.h"
19 #include "exec/address-spaces.h"
20 #include "hw/irq.h"
21 #include "net/net.h"
22 #include "hw/loader.h"
23 #include "elf.h"
24 #include "hw/intc/loongarch_ipi.h"
25 #include "hw/intc/loongarch_extioi.h"
26 #include "hw/intc/loongarch_pch_pic.h"
27 #include "hw/intc/loongarch_pch_msi.h"
28 #include "hw/pci-host/ls7a.h"
29 #include "hw/pci-host/gpex.h"
30 #include "hw/misc/unimp.h"
31 #include "hw/loongarch/fw_cfg.h"
32 #include "target/loongarch/cpu.h"
33 #include "hw/firmware/smbios.h"
34 #include "hw/acpi/aml-build.h"
35 #include "qapi/qapi-visit-common.h"
36 #include "hw/acpi/generic_event_device.h"
37 #include "hw/mem/nvdimm.h"
38 #include "sysemu/device_tree.h"
39 #include <libfdt.h>
40 #include "hw/core/sysbus-fdt.h"
41 #include "hw/platform-bus.h"
42 #include "hw/display/ramfb.h"
43 #include "hw/mem/pc-dimm.h"
44 #include "sysemu/tpm.h"
45 #include "sysemu/block-backend.h"
46 #include "hw/block/flash.h"
47 #include "qemu/error-report.h"
48 
49 
50 static void virt_flash_create(LoongArchMachineState *lams)
51 {
52     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI01);
53 
54     qdev_prop_set_uint64(dev, "sector-length", VIRT_FLASH_SECTOR_SIZE);
55     qdev_prop_set_uint8(dev, "width", 4);
56     qdev_prop_set_uint8(dev, "device-width", 2);
57     qdev_prop_set_bit(dev, "big-endian", false);
58     qdev_prop_set_uint16(dev, "id0", 0x89);
59     qdev_prop_set_uint16(dev, "id1", 0x18);
60     qdev_prop_set_uint16(dev, "id2", 0x00);
61     qdev_prop_set_uint16(dev, "id3", 0x00);
62     qdev_prop_set_string(dev, "name", "virt.flash");
63     object_property_add_child(OBJECT(lams), "virt.flash", OBJECT(dev));
64     object_property_add_alias(OBJECT(lams), "pflash",
65                               OBJECT(dev), "drive");
66 
67     lams->flash = PFLASH_CFI01(dev);
68 }
69 
70 static void virt_flash_map(LoongArchMachineState *lams,
71                            MemoryRegion *sysmem)
72 {
73     PFlashCFI01 *flash = lams->flash;
74     DeviceState *dev = DEVICE(flash);
75     hwaddr base = VIRT_FLASH_BASE;
76     hwaddr size = VIRT_FLASH_SIZE;
77 
78     assert(QEMU_IS_ALIGNED(size, VIRT_FLASH_SECTOR_SIZE));
79     assert(size / VIRT_FLASH_SECTOR_SIZE <= UINT32_MAX);
80 
81     qdev_prop_set_uint32(dev, "num-blocks", size / VIRT_FLASH_SECTOR_SIZE);
82     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
83     memory_region_add_subregion(sysmem, base,
84                                 sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 0));
85 
86 }
87 
88 static void fdt_add_flash_node(LoongArchMachineState *lams)
89 {
90     MachineState *ms = MACHINE(lams);
91     char *nodename;
92 
93     hwaddr flash_base = VIRT_FLASH_BASE;
94     hwaddr flash_size = VIRT_FLASH_SIZE;
95 
96     nodename = g_strdup_printf("/flash@%" PRIx64, flash_base);
97     qemu_fdt_add_subnode(ms->fdt, nodename);
98     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "cfi-flash");
99     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
100                                  2, flash_base, 2, flash_size);
101     qemu_fdt_setprop_cell(ms->fdt, nodename, "bank-width", 4);
102     g_free(nodename);
103 }
104 
105 static void fdt_add_rtc_node(LoongArchMachineState *lams)
106 {
107     char *nodename;
108     hwaddr base = VIRT_RTC_REG_BASE;
109     hwaddr size = VIRT_RTC_LEN;
110     MachineState *ms = MACHINE(lams);
111 
112     nodename = g_strdup_printf("/rtc@%" PRIx64, base);
113     qemu_fdt_add_subnode(ms->fdt, nodename);
114     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "loongson,ls7a-rtc");
115     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg", 2, base, 2, size);
116     g_free(nodename);
117 }
118 
119 static void fdt_add_uart_node(LoongArchMachineState *lams)
120 {
121     char *nodename;
122     hwaddr base = VIRT_UART_BASE;
123     hwaddr size = VIRT_UART_SIZE;
124     MachineState *ms = MACHINE(lams);
125 
126     nodename = g_strdup_printf("/serial@%" PRIx64, base);
127     qemu_fdt_add_subnode(ms->fdt, nodename);
128     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible", "ns16550a");
129     qemu_fdt_setprop_cells(ms->fdt, nodename, "reg", 0x0, base, 0x0, size);
130     qemu_fdt_setprop_cell(ms->fdt, nodename, "clock-frequency", 100000000);
131     qemu_fdt_setprop_string(ms->fdt, "/chosen", "stdout-path", nodename);
132     g_free(nodename);
133 }
134 
135 static void create_fdt(LoongArchMachineState *lams)
136 {
137     MachineState *ms = MACHINE(lams);
138 
139     ms->fdt = create_device_tree(&lams->fdt_size);
140     if (!ms->fdt) {
141         error_report("create_device_tree() failed");
142         exit(1);
143     }
144 
145     /* Header */
146     qemu_fdt_setprop_string(ms->fdt, "/", "compatible",
147                             "linux,dummy-loongson3");
148     qemu_fdt_setprop_cell(ms->fdt, "/", "#address-cells", 0x2);
149     qemu_fdt_setprop_cell(ms->fdt, "/", "#size-cells", 0x2);
150     qemu_fdt_add_subnode(ms->fdt, "/chosen");
151 }
152 
153 static void fdt_add_cpu_nodes(const LoongArchMachineState *lams)
154 {
155     int num;
156     const MachineState *ms = MACHINE(lams);
157     int smp_cpus = ms->smp.cpus;
158 
159     qemu_fdt_add_subnode(ms->fdt, "/cpus");
160     qemu_fdt_setprop_cell(ms->fdt, "/cpus", "#address-cells", 0x1);
161     qemu_fdt_setprop_cell(ms->fdt, "/cpus", "#size-cells", 0x0);
162 
163     /* cpu nodes */
164     for (num = smp_cpus - 1; num >= 0; num--) {
165         char *nodename = g_strdup_printf("/cpus/cpu@%d", num);
166         LoongArchCPU *cpu = LOONGARCH_CPU(qemu_get_cpu(num));
167 
168         qemu_fdt_add_subnode(ms->fdt, nodename);
169         qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "cpu");
170         qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
171                                 cpu->dtb_compatible);
172         qemu_fdt_setprop_cell(ms->fdt, nodename, "reg", num);
173         qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle",
174                               qemu_fdt_alloc_phandle(ms->fdt));
175         g_free(nodename);
176     }
177 
178     /*cpu map */
179     qemu_fdt_add_subnode(ms->fdt, "/cpus/cpu-map");
180 
181     for (num = smp_cpus - 1; num >= 0; num--) {
182         char *cpu_path = g_strdup_printf("/cpus/cpu@%d", num);
183         char *map_path;
184 
185         if (ms->smp.threads > 1) {
186             map_path = g_strdup_printf(
187                 "/cpus/cpu-map/socket%d/core%d/thread%d",
188                 num / (ms->smp.cores * ms->smp.threads),
189                 (num / ms->smp.threads) % ms->smp.cores,
190                 num % ms->smp.threads);
191         } else {
192             map_path = g_strdup_printf(
193                 "/cpus/cpu-map/socket%d/core%d",
194                 num / ms->smp.cores,
195                 num % ms->smp.cores);
196         }
197         qemu_fdt_add_path(ms->fdt, map_path);
198         qemu_fdt_setprop_phandle(ms->fdt, map_path, "cpu", cpu_path);
199 
200         g_free(map_path);
201         g_free(cpu_path);
202     }
203 }
204 
205 static void fdt_add_fw_cfg_node(const LoongArchMachineState *lams)
206 {
207     char *nodename;
208     hwaddr base = VIRT_FWCFG_BASE;
209     const MachineState *ms = MACHINE(lams);
210 
211     nodename = g_strdup_printf("/fw_cfg@%" PRIx64, base);
212     qemu_fdt_add_subnode(ms->fdt, nodename);
213     qemu_fdt_setprop_string(ms->fdt, nodename,
214                             "compatible", "qemu,fw-cfg-mmio");
215     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
216                                  2, base, 2, 0x18);
217     qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
218     g_free(nodename);
219 }
220 
221 static void fdt_add_pcie_node(const LoongArchMachineState *lams)
222 {
223     char *nodename;
224     hwaddr base_mmio = VIRT_PCI_MEM_BASE;
225     hwaddr size_mmio = VIRT_PCI_MEM_SIZE;
226     hwaddr base_pio = VIRT_PCI_IO_BASE;
227     hwaddr size_pio = VIRT_PCI_IO_SIZE;
228     hwaddr base_pcie = VIRT_PCI_CFG_BASE;
229     hwaddr size_pcie = VIRT_PCI_CFG_SIZE;
230     hwaddr base = base_pcie;
231 
232     const MachineState *ms = MACHINE(lams);
233 
234     nodename = g_strdup_printf("/pcie@%" PRIx64, base);
235     qemu_fdt_add_subnode(ms->fdt, nodename);
236     qemu_fdt_setprop_string(ms->fdt, nodename,
237                             "compatible", "pci-host-ecam-generic");
238     qemu_fdt_setprop_string(ms->fdt, nodename, "device_type", "pci");
239     qemu_fdt_setprop_cell(ms->fdt, nodename, "#address-cells", 3);
240     qemu_fdt_setprop_cell(ms->fdt, nodename, "#size-cells", 2);
241     qemu_fdt_setprop_cell(ms->fdt, nodename, "linux,pci-domain", 0);
242     qemu_fdt_setprop_cells(ms->fdt, nodename, "bus-range", 0,
243                            PCIE_MMCFG_BUS(VIRT_PCI_CFG_SIZE - 1));
244     qemu_fdt_setprop(ms->fdt, nodename, "dma-coherent", NULL, 0);
245     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
246                                  2, base_pcie, 2, size_pcie);
247     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "ranges",
248                                  1, FDT_PCI_RANGE_IOPORT, 2, VIRT_PCI_IO_OFFSET,
249                                  2, base_pio, 2, size_pio,
250                                  1, FDT_PCI_RANGE_MMIO, 2, base_mmio,
251                                  2, base_mmio, 2, size_mmio);
252     g_free(nodename);
253 }
254 
255 static void fdt_add_irqchip_node(LoongArchMachineState *lams)
256 {
257     MachineState *ms = MACHINE(lams);
258     char *nodename;
259     uint32_t irqchip_phandle;
260 
261     irqchip_phandle = qemu_fdt_alloc_phandle(ms->fdt);
262     qemu_fdt_setprop_cell(ms->fdt, "/", "interrupt-parent", irqchip_phandle);
263 
264     nodename = g_strdup_printf("/intc@%lx", VIRT_IOAPIC_REG_BASE);
265     qemu_fdt_add_subnode(ms->fdt, nodename);
266     qemu_fdt_setprop_cell(ms->fdt, nodename, "#interrupt-cells", 3);
267     qemu_fdt_setprop(ms->fdt, nodename, "interrupt-controller", NULL, 0);
268     qemu_fdt_setprop_cell(ms->fdt, nodename, "#address-cells", 0x2);
269     qemu_fdt_setprop_cell(ms->fdt, nodename, "#size-cells", 0x2);
270     qemu_fdt_setprop(ms->fdt, nodename, "ranges", NULL, 0);
271 
272     qemu_fdt_setprop_string(ms->fdt, nodename, "compatible",
273                             "loongarch,ls7a");
274 
275     qemu_fdt_setprop_sized_cells(ms->fdt, nodename, "reg",
276                                  2, VIRT_IOAPIC_REG_BASE,
277                                  2, PCH_PIC_ROUTE_ENTRY_OFFSET);
278 
279     qemu_fdt_setprop_cell(ms->fdt, nodename, "phandle", irqchip_phandle);
280     g_free(nodename);
281 }
282 
283 #define PM_BASE 0x10080000
284 #define PM_SIZE 0x100
285 #define PM_CTRL 0x10
286 
287 static void virt_build_smbios(LoongArchMachineState *lams)
288 {
289     MachineState *ms = MACHINE(lams);
290     MachineClass *mc = MACHINE_GET_CLASS(lams);
291     uint8_t *smbios_tables, *smbios_anchor;
292     size_t smbios_tables_len, smbios_anchor_len;
293     const char *product = "QEMU Virtual Machine";
294 
295     if (!lams->fw_cfg) {
296         return;
297     }
298 
299     smbios_set_defaults("QEMU", product, mc->name, false,
300                         true, SMBIOS_ENTRY_POINT_TYPE_64);
301 
302     smbios_get_tables(ms, NULL, 0, &smbios_tables, &smbios_tables_len,
303                       &smbios_anchor, &smbios_anchor_len, &error_fatal);
304 
305     if (smbios_anchor) {
306         fw_cfg_add_file(lams->fw_cfg, "etc/smbios/smbios-tables",
307                         smbios_tables, smbios_tables_len);
308         fw_cfg_add_file(lams->fw_cfg, "etc/smbios/smbios-anchor",
309                         smbios_anchor, smbios_anchor_len);
310     }
311 }
312 
313 static void virt_machine_done(Notifier *notifier, void *data)
314 {
315     LoongArchMachineState *lams = container_of(notifier,
316                                         LoongArchMachineState, machine_done);
317     virt_build_smbios(lams);
318     loongarch_acpi_setup(lams);
319 }
320 
321 static void virt_powerdown_req(Notifier *notifier, void *opaque)
322 {
323     LoongArchMachineState *s = container_of(notifier,
324                                    LoongArchMachineState, powerdown_notifier);
325 
326     acpi_send_event(s->acpi_ged, ACPI_POWER_DOWN_STATUS);
327 }
328 
329 struct memmap_entry {
330     uint64_t address;
331     uint64_t length;
332     uint32_t type;
333     uint32_t reserved;
334 };
335 
336 static struct memmap_entry *memmap_table;
337 static unsigned memmap_entries;
338 
339 static void memmap_add_entry(uint64_t address, uint64_t length, uint32_t type)
340 {
341     /* Ensure there are no duplicate entries. */
342     for (unsigned i = 0; i < memmap_entries; i++) {
343         assert(memmap_table[i].address != address);
344     }
345 
346     memmap_table = g_renew(struct memmap_entry, memmap_table,
347                            memmap_entries + 1);
348     memmap_table[memmap_entries].address = cpu_to_le64(address);
349     memmap_table[memmap_entries].length = cpu_to_le64(length);
350     memmap_table[memmap_entries].type = cpu_to_le32(type);
351     memmap_table[memmap_entries].reserved = 0;
352     memmap_entries++;
353 }
354 
355 /*
356  * This is a placeholder for missing ACPI,
357  * and will eventually be replaced.
358  */
359 static uint64_t loongarch_virt_pm_read(void *opaque, hwaddr addr, unsigned size)
360 {
361     return 0;
362 }
363 
364 static void loongarch_virt_pm_write(void *opaque, hwaddr addr,
365                                uint64_t val, unsigned size)
366 {
367     if (addr != PM_CTRL) {
368         return;
369     }
370 
371     switch (val) {
372     case 0x00:
373         qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
374         return;
375     case 0xff:
376         qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
377         return;
378     default:
379         return;
380     }
381 }
382 
383 static const MemoryRegionOps loongarch_virt_pm_ops = {
384     .read  = loongarch_virt_pm_read,
385     .write = loongarch_virt_pm_write,
386     .endianness = DEVICE_NATIVE_ENDIAN,
387     .valid = {
388         .min_access_size = 1,
389         .max_access_size = 1
390     }
391 };
392 
393 static struct _loaderparams {
394     uint64_t ram_size;
395     const char *kernel_filename;
396     const char *kernel_cmdline;
397     const char *initrd_filename;
398 } loaderparams;
399 
400 static uint64_t cpu_loongarch_virt_to_phys(void *opaque, uint64_t addr)
401 {
402     return addr & MAKE_64BIT_MASK(0, TARGET_PHYS_ADDR_SPACE_BITS);
403 }
404 
405 static int64_t load_kernel_info(void)
406 {
407     uint64_t kernel_entry, kernel_low, kernel_high;
408     ssize_t kernel_size;
409 
410     kernel_size = load_elf(loaderparams.kernel_filename, NULL,
411                            cpu_loongarch_virt_to_phys, NULL,
412                            &kernel_entry, &kernel_low,
413                            &kernel_high, NULL, 0,
414                            EM_LOONGARCH, 1, 0);
415 
416     if (kernel_size < 0) {
417         error_report("could not load kernel '%s': %s",
418                      loaderparams.kernel_filename,
419                      load_elf_strerror(kernel_size));
420         exit(1);
421     }
422     return kernel_entry;
423 }
424 
425 static DeviceState *create_acpi_ged(DeviceState *pch_pic, LoongArchMachineState *lams)
426 {
427     DeviceState *dev;
428     MachineState *ms = MACHINE(lams);
429     uint32_t event = ACPI_GED_PWR_DOWN_EVT;
430 
431     if (ms->ram_slots) {
432         event |= ACPI_GED_MEM_HOTPLUG_EVT;
433     }
434     dev = qdev_new(TYPE_ACPI_GED);
435     qdev_prop_set_uint32(dev, "ged-event", event);
436 
437     /* ged event */
438     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, VIRT_GED_EVT_ADDR);
439     /* memory hotplug */
440     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 1, VIRT_GED_MEM_ADDR);
441     /* ged regs used for reset and power down */
442     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, VIRT_GED_REG_ADDR);
443 
444     sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0,
445                        qdev_get_gpio_in(pch_pic, VIRT_SCI_IRQ - VIRT_GSI_BASE));
446     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
447     return dev;
448 }
449 
450 static DeviceState *create_platform_bus(DeviceState *pch_pic)
451 {
452     DeviceState *dev;
453     SysBusDevice *sysbus;
454     int i, irq;
455     MemoryRegion *sysmem = get_system_memory();
456 
457     dev = qdev_new(TYPE_PLATFORM_BUS_DEVICE);
458     dev->id = g_strdup(TYPE_PLATFORM_BUS_DEVICE);
459     qdev_prop_set_uint32(dev, "num_irqs", VIRT_PLATFORM_BUS_NUM_IRQS);
460     qdev_prop_set_uint32(dev, "mmio_size", VIRT_PLATFORM_BUS_SIZE);
461     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
462 
463     sysbus = SYS_BUS_DEVICE(dev);
464     for (i = 0; i < VIRT_PLATFORM_BUS_NUM_IRQS; i++) {
465         irq = VIRT_PLATFORM_BUS_IRQ - VIRT_GSI_BASE + i;
466         sysbus_connect_irq(sysbus, i, qdev_get_gpio_in(pch_pic, irq));
467     }
468 
469     memory_region_add_subregion(sysmem,
470                                 VIRT_PLATFORM_BUS_BASEADDRESS,
471                                 sysbus_mmio_get_region(sysbus, 0));
472     return dev;
473 }
474 
475 static void loongarch_devices_init(DeviceState *pch_pic, LoongArchMachineState *lams)
476 {
477     MachineClass *mc = MACHINE_GET_CLASS(lams);
478     DeviceState *gpex_dev;
479     SysBusDevice *d;
480     PCIBus *pci_bus;
481     MemoryRegion *ecam_alias, *ecam_reg, *pio_alias, *pio_reg;
482     MemoryRegion *mmio_alias, *mmio_reg, *pm_mem;
483     int i;
484 
485     gpex_dev = qdev_new(TYPE_GPEX_HOST);
486     d = SYS_BUS_DEVICE(gpex_dev);
487     sysbus_realize_and_unref(d, &error_fatal);
488     pci_bus = PCI_HOST_BRIDGE(gpex_dev)->bus;
489     lams->pci_bus = pci_bus;
490 
491     /* Map only part size_ecam bytes of ECAM space */
492     ecam_alias = g_new0(MemoryRegion, 1);
493     ecam_reg = sysbus_mmio_get_region(d, 0);
494     memory_region_init_alias(ecam_alias, OBJECT(gpex_dev), "pcie-ecam",
495                              ecam_reg, 0, VIRT_PCI_CFG_SIZE);
496     memory_region_add_subregion(get_system_memory(), VIRT_PCI_CFG_BASE,
497                                 ecam_alias);
498 
499     /* Map PCI mem space */
500     mmio_alias = g_new0(MemoryRegion, 1);
501     mmio_reg = sysbus_mmio_get_region(d, 1);
502     memory_region_init_alias(mmio_alias, OBJECT(gpex_dev), "pcie-mmio",
503                              mmio_reg, VIRT_PCI_MEM_BASE, VIRT_PCI_MEM_SIZE);
504     memory_region_add_subregion(get_system_memory(), VIRT_PCI_MEM_BASE,
505                                 mmio_alias);
506 
507     /* Map PCI IO port space. */
508     pio_alias = g_new0(MemoryRegion, 1);
509     pio_reg = sysbus_mmio_get_region(d, 2);
510     memory_region_init_alias(pio_alias, OBJECT(gpex_dev), "pcie-io", pio_reg,
511                              VIRT_PCI_IO_OFFSET, VIRT_PCI_IO_SIZE);
512     memory_region_add_subregion(get_system_memory(), VIRT_PCI_IO_BASE,
513                                 pio_alias);
514 
515     for (i = 0; i < GPEX_NUM_IRQS; i++) {
516         sysbus_connect_irq(d, i,
517                            qdev_get_gpio_in(pch_pic, 16 + i));
518         gpex_set_irq_num(GPEX_HOST(gpex_dev), i, 16 + i);
519     }
520 
521     serial_mm_init(get_system_memory(), VIRT_UART_BASE, 0,
522                    qdev_get_gpio_in(pch_pic,
523                                     VIRT_UART_IRQ - VIRT_GSI_BASE),
524                    115200, serial_hd(0), DEVICE_LITTLE_ENDIAN);
525     fdt_add_uart_node(lams);
526 
527     /* Network init */
528     for (i = 0; i < nb_nics; i++) {
529         NICInfo *nd = &nd_table[i];
530 
531         if (!nd->model) {
532             nd->model = g_strdup(mc->default_nic);
533         }
534 
535         pci_nic_init_nofail(nd, pci_bus, nd->model, NULL);
536     }
537 
538     /*
539      * There are some invalid guest memory access.
540      * Create some unimplemented devices to emulate this.
541      */
542     create_unimplemented_device("pci-dma-cfg", 0x1001041c, 0x4);
543     sysbus_create_simple("ls7a_rtc", VIRT_RTC_REG_BASE,
544                          qdev_get_gpio_in(pch_pic,
545                          VIRT_RTC_IRQ - VIRT_GSI_BASE));
546     fdt_add_rtc_node(lams);
547 
548     pm_mem = g_new(MemoryRegion, 1);
549     memory_region_init_io(pm_mem, NULL, &loongarch_virt_pm_ops,
550                           NULL, "loongarch_virt_pm", PM_SIZE);
551     memory_region_add_subregion(get_system_memory(), PM_BASE, pm_mem);
552     /* acpi ged */
553     lams->acpi_ged = create_acpi_ged(pch_pic, lams);
554     /* platform bus */
555     lams->platform_bus_dev = create_platform_bus(pch_pic);
556 }
557 
558 static void loongarch_irq_init(LoongArchMachineState *lams)
559 {
560     MachineState *ms = MACHINE(lams);
561     DeviceState *pch_pic, *pch_msi, *cpudev;
562     DeviceState *ipi, *extioi;
563     SysBusDevice *d;
564     LoongArchCPU *lacpu;
565     CPULoongArchState *env;
566     CPUState *cpu_state;
567     int cpu, pin, i, start, num;
568 
569     extioi = qdev_new(TYPE_LOONGARCH_EXTIOI);
570     sysbus_realize_and_unref(SYS_BUS_DEVICE(extioi), &error_fatal);
571 
572     /*
573      * The connection of interrupts:
574      *   +-----+    +---------+     +-------+
575      *   | IPI |--> | CPUINTC | <-- | Timer |
576      *   +-----+    +---------+     +-------+
577      *                  ^
578      *                  |
579      *            +---------+
580      *            | EIOINTC |
581      *            +---------+
582      *             ^       ^
583      *             |       |
584      *      +---------+ +---------+
585      *      | PCH-PIC | | PCH-MSI |
586      *      +---------+ +---------+
587      *        ^      ^          ^
588      *        |      |          |
589      * +--------+ +---------+ +---------+
590      * | UARTs  | | Devices | | Devices |
591      * +--------+ +---------+ +---------+
592      */
593     for (cpu = 0; cpu < ms->smp.cpus; cpu++) {
594         cpu_state = qemu_get_cpu(cpu);
595         cpudev = DEVICE(cpu_state);
596         lacpu = LOONGARCH_CPU(cpu_state);
597         env = &(lacpu->env);
598 
599         ipi = qdev_new(TYPE_LOONGARCH_IPI);
600         sysbus_realize_and_unref(SYS_BUS_DEVICE(ipi), &error_fatal);
601 
602         /* connect ipi irq to cpu irq */
603         qdev_connect_gpio_out(ipi, 0, qdev_get_gpio_in(cpudev, IRQ_IPI));
604         /* IPI iocsr memory region */
605         memory_region_add_subregion(&env->system_iocsr, SMP_IPI_MAILBOX,
606                                     sysbus_mmio_get_region(SYS_BUS_DEVICE(ipi),
607                                     0));
608         memory_region_add_subregion(&env->system_iocsr, MAIL_SEND_ADDR,
609                                     sysbus_mmio_get_region(SYS_BUS_DEVICE(ipi),
610                                     1));
611         /*
612 	 * extioi iocsr memory region
613 	 * only one extioi is added on loongarch virt machine
614 	 * external device interrupt can only be routed to cpu 0-3
615 	 */
616 	if (cpu < EXTIOI_CPUS)
617             memory_region_add_subregion(&env->system_iocsr, APIC_BASE,
618                                 sysbus_mmio_get_region(SYS_BUS_DEVICE(extioi),
619                                 cpu));
620     }
621 
622     /*
623      * connect ext irq to the cpu irq
624      * cpu_pin[9:2] <= intc_pin[7:0]
625      */
626     for (cpu = 0; cpu < MIN(ms->smp.cpus, EXTIOI_CPUS); cpu++) {
627         cpudev = DEVICE(qemu_get_cpu(cpu));
628         for (pin = 0; pin < LS3A_INTC_IP; pin++) {
629             qdev_connect_gpio_out(extioi, (cpu * 8 + pin),
630                                   qdev_get_gpio_in(cpudev, pin + 2));
631         }
632     }
633 
634     pch_pic = qdev_new(TYPE_LOONGARCH_PCH_PIC);
635     num = VIRT_PCH_PIC_IRQ_NUM;
636     qdev_prop_set_uint32(pch_pic, "pch_pic_irq_num", num);
637     d = SYS_BUS_DEVICE(pch_pic);
638     sysbus_realize_and_unref(d, &error_fatal);
639     memory_region_add_subregion(get_system_memory(), VIRT_IOAPIC_REG_BASE,
640                             sysbus_mmio_get_region(d, 0));
641     memory_region_add_subregion(get_system_memory(),
642                             VIRT_IOAPIC_REG_BASE + PCH_PIC_ROUTE_ENTRY_OFFSET,
643                             sysbus_mmio_get_region(d, 1));
644     memory_region_add_subregion(get_system_memory(),
645                             VIRT_IOAPIC_REG_BASE + PCH_PIC_INT_STATUS_LO,
646                             sysbus_mmio_get_region(d, 2));
647 
648     /* Connect pch_pic irqs to extioi */
649     for (int i = 0; i < num; i++) {
650         qdev_connect_gpio_out(DEVICE(d), i, qdev_get_gpio_in(extioi, i));
651     }
652 
653     pch_msi = qdev_new(TYPE_LOONGARCH_PCH_MSI);
654     start   =  num;
655     num = EXTIOI_IRQS - start;
656     qdev_prop_set_uint32(pch_msi, "msi_irq_base", start);
657     qdev_prop_set_uint32(pch_msi, "msi_irq_num", num);
658     d = SYS_BUS_DEVICE(pch_msi);
659     sysbus_realize_and_unref(d, &error_fatal);
660     sysbus_mmio_map(d, 0, VIRT_PCH_MSI_ADDR_LOW);
661     for (i = 0; i < num; i++) {
662         /* Connect pch_msi irqs to extioi */
663         qdev_connect_gpio_out(DEVICE(d), i,
664                               qdev_get_gpio_in(extioi, i + start));
665     }
666 
667     loongarch_devices_init(pch_pic, lams);
668 }
669 
670 static void loongarch_firmware_init(LoongArchMachineState *lams)
671 {
672     char *filename = MACHINE(lams)->firmware;
673     char *bios_name = NULL;
674     int bios_size;
675 
676     lams->bios_loaded = false;
677 
678     virt_flash_map(lams, get_system_memory());
679 
680     if (filename) {
681         bios_name = qemu_find_file(QEMU_FILE_TYPE_BIOS, filename);
682         if (!bios_name) {
683             error_report("Could not find ROM image '%s'", filename);
684             exit(1);
685         }
686 
687         bios_size = load_image_targphys(bios_name, VIRT_BIOS_BASE, VIRT_BIOS_SIZE);
688         if (bios_size < 0) {
689             error_report("Could not load ROM image '%s'", bios_name);
690             exit(1);
691         }
692 
693         g_free(bios_name);
694 
695         memory_region_init_ram(&lams->bios, NULL, "loongarch.bios",
696                                VIRT_BIOS_SIZE, &error_fatal);
697         memory_region_set_readonly(&lams->bios, true);
698         memory_region_add_subregion(get_system_memory(), VIRT_BIOS_BASE, &lams->bios);
699         lams->bios_loaded = true;
700     }
701 
702 }
703 
704 static void reset_load_elf(void *opaque)
705 {
706     LoongArchCPU *cpu = opaque;
707     CPULoongArchState *env = &cpu->env;
708 
709     cpu_reset(CPU(cpu));
710     if (env->load_elf) {
711         cpu_set_pc(CPU(cpu), env->elf_address);
712     }
713 }
714 
715 static void fw_cfg_add_kernel_info(FWCfgState *fw_cfg)
716 {
717     /*
718      * Expose the kernel, the command line, and the initrd in fw_cfg.
719      * We don't process them here at all, it's all left to the
720      * firmware.
721      */
722     load_image_to_fw_cfg(fw_cfg,
723                          FW_CFG_KERNEL_SIZE, FW_CFG_KERNEL_DATA,
724                          loaderparams.kernel_filename,
725                          false);
726 
727     if (loaderparams.initrd_filename) {
728         load_image_to_fw_cfg(fw_cfg,
729                              FW_CFG_INITRD_SIZE, FW_CFG_INITRD_DATA,
730                              loaderparams.initrd_filename, false);
731     }
732 
733     if (loaderparams.kernel_cmdline) {
734         fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,
735                        strlen(loaderparams.kernel_cmdline) + 1);
736         fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA,
737                           loaderparams.kernel_cmdline);
738     }
739 }
740 
741 static void loongarch_firmware_boot(LoongArchMachineState *lams)
742 {
743     fw_cfg_add_kernel_info(lams->fw_cfg);
744 }
745 
746 static void loongarch_direct_kernel_boot(LoongArchMachineState *lams)
747 {
748     MachineState *machine = MACHINE(lams);
749     int64_t kernel_addr = 0;
750     LoongArchCPU *lacpu;
751     int i;
752 
753     kernel_addr = load_kernel_info();
754     if (!machine->firmware) {
755         for (i = 0; i < machine->smp.cpus; i++) {
756             lacpu = LOONGARCH_CPU(qemu_get_cpu(i));
757             lacpu->env.load_elf = true;
758             lacpu->env.elf_address = kernel_addr;
759         }
760     }
761 }
762 
763 static void loongarch_init(MachineState *machine)
764 {
765     LoongArchCPU *lacpu;
766     const char *cpu_model = machine->cpu_type;
767     ram_addr_t offset = 0;
768     ram_addr_t ram_size = machine->ram_size;
769     uint64_t highram_size = 0;
770     MemoryRegion *address_space_mem = get_system_memory();
771     LoongArchMachineState *lams = LOONGARCH_MACHINE(machine);
772     int i;
773     hwaddr fdt_base;
774 
775     if (!cpu_model) {
776         cpu_model = LOONGARCH_CPU_TYPE_NAME("la464");
777     }
778 
779     if (!strstr(cpu_model, "la464")) {
780         error_report("LoongArch/TCG needs cpu type la464");
781         exit(1);
782     }
783 
784     if (ram_size < 1 * GiB) {
785         error_report("ram_size must be greater than 1G.");
786         exit(1);
787     }
788     create_fdt(lams);
789     /* Init CPUs */
790     for (i = 0; i < machine->smp.cpus; i++) {
791         cpu_create(machine->cpu_type);
792     }
793     fdt_add_cpu_nodes(lams);
794     /* Add memory region */
795     memory_region_init_alias(&lams->lowmem, NULL, "loongarch.lowram",
796                              machine->ram, 0, 256 * MiB);
797     memory_region_add_subregion(address_space_mem, offset, &lams->lowmem);
798     offset += 256 * MiB;
799     memmap_add_entry(0, 256 * MiB, 1);
800     highram_size = ram_size - 256 * MiB;
801     memory_region_init_alias(&lams->highmem, NULL, "loongarch.highmem",
802                              machine->ram, offset, highram_size);
803     memory_region_add_subregion(address_space_mem, 0x90000000, &lams->highmem);
804     memmap_add_entry(0x90000000, highram_size, 1);
805 
806     /* initialize device memory address space */
807     if (machine->ram_size < machine->maxram_size) {
808         machine->device_memory = g_malloc0(sizeof(*machine->device_memory));
809         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
810 
811         if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {
812             error_report("unsupported amount of memory slots: %"PRIu64,
813                          machine->ram_slots);
814             exit(EXIT_FAILURE);
815         }
816 
817         if (QEMU_ALIGN_UP(machine->maxram_size,
818                           TARGET_PAGE_SIZE) != machine->maxram_size) {
819             error_report("maximum memory size must by aligned to multiple of "
820                          "%d bytes", TARGET_PAGE_SIZE);
821             exit(EXIT_FAILURE);
822         }
823         /* device memory base is the top of high memory address. */
824         machine->device_memory->base = 0x90000000 + highram_size;
825         machine->device_memory->base =
826             ROUND_UP(machine->device_memory->base, 1 * GiB);
827 
828         memory_region_init(&machine->device_memory->mr, OBJECT(lams),
829                            "device-memory", device_mem_size);
830         memory_region_add_subregion(address_space_mem, machine->device_memory->base,
831                                     &machine->device_memory->mr);
832     }
833 
834     /* Add isa io region */
835     memory_region_init_alias(&lams->isa_io, NULL, "isa-io",
836                              get_system_io(), 0, VIRT_ISA_IO_SIZE);
837     memory_region_add_subregion(address_space_mem, VIRT_ISA_IO_BASE,
838                                 &lams->isa_io);
839     /* load the BIOS image. */
840     loongarch_firmware_init(lams);
841 
842     /* fw_cfg init */
843     lams->fw_cfg = loongarch_fw_cfg_init(ram_size, machine);
844     rom_set_fw(lams->fw_cfg);
845     if (lams->fw_cfg != NULL) {
846         fw_cfg_add_file(lams->fw_cfg, "etc/memmap",
847                         memmap_table,
848                         sizeof(struct memmap_entry) * (memmap_entries));
849     }
850     fdt_add_fw_cfg_node(lams);
851     loaderparams.ram_size = ram_size;
852     loaderparams.kernel_filename = machine->kernel_filename;
853     loaderparams.kernel_cmdline = machine->kernel_cmdline;
854     loaderparams.initrd_filename = machine->initrd_filename;
855     /* load the kernel. */
856     if (loaderparams.kernel_filename) {
857         if (lams->bios_loaded) {
858             loongarch_firmware_boot(lams);
859         } else {
860             loongarch_direct_kernel_boot(lams);
861         }
862     }
863     fdt_add_flash_node(lams);
864     /* register reset function */
865     for (i = 0; i < machine->smp.cpus; i++) {
866         lacpu = LOONGARCH_CPU(qemu_get_cpu(i));
867         qemu_register_reset(reset_load_elf, lacpu);
868     }
869     /* Initialize the IO interrupt subsystem */
870     loongarch_irq_init(lams);
871     fdt_add_irqchip_node(lams);
872     platform_bus_add_all_fdt_nodes(machine->fdt, "/intc",
873                                    VIRT_PLATFORM_BUS_BASEADDRESS,
874                                    VIRT_PLATFORM_BUS_SIZE,
875                                    VIRT_PLATFORM_BUS_IRQ);
876     lams->machine_done.notify = virt_machine_done;
877     qemu_add_machine_init_done_notifier(&lams->machine_done);
878      /* connect powerdown request */
879     lams->powerdown_notifier.notify = virt_powerdown_req;
880     qemu_register_powerdown_notifier(&lams->powerdown_notifier);
881 
882     fdt_add_pcie_node(lams);
883     /*
884      * Since lowmem region starts from 0 and Linux kernel legacy start address
885      * at 2 MiB, FDT base address is located at 1 MiB to avoid NULL pointer
886      * access. FDT size limit with 1 MiB.
887      * Put the FDT into the memory map as a ROM image: this will ensure
888      * the FDT is copied again upon reset, even if addr points into RAM.
889      */
890     fdt_base = 1 * MiB;
891     qemu_fdt_dumpdtb(machine->fdt, lams->fdt_size);
892     rom_add_blob_fixed("fdt", machine->fdt, lams->fdt_size, fdt_base);
893 }
894 
895 bool loongarch_is_acpi_enabled(LoongArchMachineState *lams)
896 {
897     if (lams->acpi == ON_OFF_AUTO_OFF) {
898         return false;
899     }
900     return true;
901 }
902 
903 static void loongarch_get_acpi(Object *obj, Visitor *v, const char *name,
904                                void *opaque, Error **errp)
905 {
906     LoongArchMachineState *lams = LOONGARCH_MACHINE(obj);
907     OnOffAuto acpi = lams->acpi;
908 
909     visit_type_OnOffAuto(v, name, &acpi, errp);
910 }
911 
912 static void loongarch_set_acpi(Object *obj, Visitor *v, const char *name,
913                                void *opaque, Error **errp)
914 {
915     LoongArchMachineState *lams = LOONGARCH_MACHINE(obj);
916 
917     visit_type_OnOffAuto(v, name, &lams->acpi, errp);
918 }
919 
920 static void loongarch_machine_initfn(Object *obj)
921 {
922     LoongArchMachineState *lams = LOONGARCH_MACHINE(obj);
923 
924     lams->acpi = ON_OFF_AUTO_AUTO;
925     lams->oem_id = g_strndup(ACPI_BUILD_APPNAME6, 6);
926     lams->oem_table_id = g_strndup(ACPI_BUILD_APPNAME8, 8);
927     virt_flash_create(lams);
928 }
929 
930 static bool memhp_type_supported(DeviceState *dev)
931 {
932     /* we only support pc dimm now */
933     return object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) &&
934            !object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
935 }
936 
937 static void virt_mem_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
938                                  Error **errp)
939 {
940     pc_dimm_pre_plug(PC_DIMM(dev), MACHINE(hotplug_dev), NULL, errp);
941 }
942 
943 static void virt_machine_device_pre_plug(HotplugHandler *hotplug_dev,
944                                             DeviceState *dev, Error **errp)
945 {
946     if (memhp_type_supported(dev)) {
947         virt_mem_pre_plug(hotplug_dev, dev, errp);
948     }
949 }
950 
951 static void virt_mem_unplug_request(HotplugHandler *hotplug_dev,
952                                      DeviceState *dev, Error **errp)
953 {
954     LoongArchMachineState *lams = LOONGARCH_MACHINE(hotplug_dev);
955 
956     /* the acpi ged is always exist */
957     hotplug_handler_unplug_request(HOTPLUG_HANDLER(lams->acpi_ged), dev,
958                                    errp);
959 }
960 
961 static void virt_machine_device_unplug_request(HotplugHandler *hotplug_dev,
962                                           DeviceState *dev, Error **errp)
963 {
964     if (memhp_type_supported(dev)) {
965         virt_mem_unplug_request(hotplug_dev, dev, errp);
966     }
967 }
968 
969 static void virt_mem_unplug(HotplugHandler *hotplug_dev,
970                              DeviceState *dev, Error **errp)
971 {
972     LoongArchMachineState *lams = LOONGARCH_MACHINE(hotplug_dev);
973 
974     hotplug_handler_unplug(HOTPLUG_HANDLER(lams->acpi_ged), dev, errp);
975     pc_dimm_unplug(PC_DIMM(dev), MACHINE(lams));
976     qdev_unrealize(dev);
977 }
978 
979 static void virt_machine_device_unplug(HotplugHandler *hotplug_dev,
980                                           DeviceState *dev, Error **errp)
981 {
982     if (memhp_type_supported(dev)) {
983         virt_mem_unplug(hotplug_dev, dev, errp);
984     }
985 }
986 
987 static void virt_mem_plug(HotplugHandler *hotplug_dev,
988                              DeviceState *dev, Error **errp)
989 {
990     LoongArchMachineState *lams = LOONGARCH_MACHINE(hotplug_dev);
991 
992     pc_dimm_plug(PC_DIMM(dev), MACHINE(lams));
993     hotplug_handler_plug(HOTPLUG_HANDLER(lams->acpi_ged),
994                          dev, &error_abort);
995 }
996 
997 static void loongarch_machine_device_plug_cb(HotplugHandler *hotplug_dev,
998                                         DeviceState *dev, Error **errp)
999 {
1000     LoongArchMachineState *lams = LOONGARCH_MACHINE(hotplug_dev);
1001     MachineClass *mc = MACHINE_GET_CLASS(lams);
1002 
1003     if (device_is_dynamic_sysbus(mc, dev)) {
1004         if (lams->platform_bus_dev) {
1005             platform_bus_link_device(PLATFORM_BUS_DEVICE(lams->platform_bus_dev),
1006                                      SYS_BUS_DEVICE(dev));
1007         }
1008     } else if (memhp_type_supported(dev)) {
1009         virt_mem_plug(hotplug_dev, dev, errp);
1010     }
1011 }
1012 
1013 static HotplugHandler *virt_machine_get_hotplug_handler(MachineState *machine,
1014                                                         DeviceState *dev)
1015 {
1016     MachineClass *mc = MACHINE_GET_CLASS(machine);
1017 
1018     if (device_is_dynamic_sysbus(mc, dev) ||
1019         memhp_type_supported(dev)) {
1020         return HOTPLUG_HANDLER(machine);
1021     }
1022     return NULL;
1023 }
1024 
1025 static void loongarch_class_init(ObjectClass *oc, void *data)
1026 {
1027     MachineClass *mc = MACHINE_CLASS(oc);
1028     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
1029 
1030     mc->desc = "Loongson-3A5000 LS7A1000 machine";
1031     mc->init = loongarch_init;
1032     mc->default_ram_size = 1 * GiB;
1033     mc->default_cpu_type = LOONGARCH_CPU_TYPE_NAME("la464");
1034     mc->default_ram_id = "loongarch.ram";
1035     mc->max_cpus = LOONGARCH_MAX_CPUS;
1036     mc->is_default = 1;
1037     mc->default_kernel_irqchip_split = false;
1038     mc->block_default_type = IF_VIRTIO;
1039     mc->default_boot_order = "c";
1040     mc->no_cdrom = 1;
1041     mc->get_hotplug_handler = virt_machine_get_hotplug_handler;
1042     mc->default_nic = "virtio-net-pci";
1043     hc->plug = loongarch_machine_device_plug_cb;
1044     hc->pre_plug = virt_machine_device_pre_plug;
1045     hc->unplug_request = virt_machine_device_unplug_request;
1046     hc->unplug = virt_machine_device_unplug;
1047 
1048     object_class_property_add(oc, "acpi", "OnOffAuto",
1049         loongarch_get_acpi, loongarch_set_acpi,
1050         NULL, NULL);
1051     object_class_property_set_description(oc, "acpi",
1052         "Enable ACPI");
1053     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_RAMFB_DEVICE);
1054 #ifdef CONFIG_TPM
1055     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
1056 #endif
1057 }
1058 
1059 static const TypeInfo loongarch_machine_types[] = {
1060     {
1061         .name           = TYPE_LOONGARCH_MACHINE,
1062         .parent         = TYPE_MACHINE,
1063         .instance_size  = sizeof(LoongArchMachineState),
1064         .class_init     = loongarch_class_init,
1065         .instance_init = loongarch_machine_initfn,
1066         .interfaces = (InterfaceInfo[]) {
1067          { TYPE_HOTPLUG_HANDLER },
1068          { }
1069         },
1070     }
1071 };
1072 
1073 DEFINE_TYPES(loongarch_machine_types)
1074