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