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