/*
 * hw/arm/ugur_m4.c
 *
 * Custom ARMv7-M (Cortex-M4) QEMU machine — uses only stock QEMU peripherals.
 *
 * ┌─────────────────────────────────────────────────────────────────┐
 * │                  TYPE_ARMV7M  (Cortex-M4)                       │
 * │   CPU core  │  NVIC (82 ext IRQs)    │  SysTick  │  SCB        │
 * └──────┬───────────────┬──────────────────────┬────────────────────┘
 *   IRQ[37]          IRQ[28] IRQ[29]         IRQ[6]
 *    PL011          SP804-T1  SP804-T2         PL061
 *  (UART0)          (Timer 1) (Timer 2)        (GPIO)
 * 0x40000000       0x40001000               0x40002000
 *
 * Memory map
 * ----------
 *  0x00000000  Flash alias  1024 KB  (boot alias of 0x08000000)
 *  0x08000000  Flash (ROM)  1024 KB   loaded from -kernel ELF
 *  0x10000000  CCMRAM        64 KB
 *  0x20000000  SRAM         128 KB
 *  0x40000000  PL011 UART0  4 KB     → NVIC IRQ 37 (USART1)
 *  0x40001000  SP804 Timers 4 KB     → NVIC IRQ 28 (TIM2), IRQ 29 (TIM3)
 *  0x40002000  PL061 GPIO   4 KB     → NVIC IRQ 6  (EXTI0)
 *  0xE000E000  NVIC / SCB           (inside TYPE_ARMV7M, automatic)
 *
 * Boot
 * ----
 *  qemu-system-arm -M my-machine -kernel firmware.elf -serial stdio -nographic
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "qemu/osdep.h"

#include "qapi/error.h"             // error_fatal passed to realize calls
#include "hw/char/pl011.h"          // pl011_create() — we keep no PL011 pointer in the struct
#include "hw/arm/machines-qom.h"
#include "hw/sysbus.h"              // SysBusDevice* local variable only
#include "hw/qdev-clock.h"
#include "hw/misc/unimp.h"          // create_unimplemented_device()
#include "hw/qdev-properties.h"     // qdev_prop_set_*() setters
#include "hw/arm/boot.h"            // arm_load_kernel(), struct arm_boot_info
#include "system/address-spaces.h"  // get_system_memory()
#include "system/system.h"          // serial_hd(0)
#include "hw/clock.h"
#include "hw/arm/ugur_m4.h"         // UgurM4State, #define constants, TYPE_UGUR_M4_MACHINE




static void ugur_m4_init(MachineState *machine)
{
    UgurM4State *s   = UGUR_M4_MACHINE(machine);
    MemoryRegion   *sys = get_system_memory();
    DeviceState    *nvic;
    DeviceState    *dev;
    SysBusDevice   *sbd;
    Clock          *sysclk;
    Clock          *refclk;

    // 1. Cortex-M4 CPU + integrated NVIC
    /*
     * TYPE_ARMV7M is QEMU's all-in-one Cortex-M object.  It exposes:
     *   • The ARMv7-M CPU (with optional FPU)
     *   • NVIC with `num-irq` external interrupt lines
     *   • SysTick
     *   • System Control Block (SCB)
     *
     * We feed it the system address space so the CPU can address all
     * peripherals. The vector table is read from Flash at address 0x0.
     */
    object_initialize_child(OBJECT(s), "mcu", &s->mcu, TYPE_ARMV7M);
    nvic = DEVICE(&s->mcu);
    sysclk = clock_new(OBJECT(machine), "SYSCLK");
    refclk = clock_new(OBJECT(machine), "REFCLK");
    clock_set_hz(sysclk, 100000000);
    clock_set_hz(refclk, 1000000);
    qdev_connect_clock_in(nvic, "cpuclk", sysclk);
    qdev_connect_clock_in(nvic, "refclk", refclk);

    // 2. Flash (ROM)
    memory_region_init_rom(&s->flash, OBJECT(nvic), "ugur-m4.flash",
                           UGUR_M4_FLASH_SIZE, &error_fatal);
    memory_region_add_subregion(sys, UGUR_M4_FLASH_BASE, &s->flash);
    memory_region_init_alias(&s->flash_alias, OBJECT(machine),
                             "ugur-m4.flash.alias", &s->flash, 0,
                             UGUR_M4_FLASH_SIZE);
    memory_region_add_subregion(sys, UGUR_M4_FLASH_ALIAS_BASE, &s->flash_alias);

    // 3. SRAM
    memory_region_init_ram(&s->sram, OBJECT(nvic), "ugur-m4.sram",
                           UGUR_M4_SRAM_SIZE, &error_fatal);
    memory_region_add_subregion(sys, UGUR_M4_SRAM_BASE, &s->sram);

    // 4. CCMRAM
    memory_region_init_ram(&s->ccmram, OBJECT(nvic), "ugur-m4.ccmram",
                           UGUR_M4_CCMRAM_SIZE, &error_fatal);
    memory_region_add_subregion(sys, UGUR_M4_CCMRAM_BASE, &s->ccmram);

    qdev_prop_set_string(nvic, "cpu-type",
                         ARM_CPU_TYPE_NAME("cortex-m4"));
    qdev_prop_set_uint32(nvic, "num-irq", UGUR_M4_NUM_IRQ);
    object_property_set_link(OBJECT(&s->mcu), "memory",
                             OBJECT(sys), &error_fatal);
    sysbus_realize(SYS_BUS_DEVICE(&s->mcu), &error_fatal);

    // 5. PL011 UART
    /*
     * pl011_create() is a QEMU convenience wrapper that:
     *   - Creates the device object
     *   - Maps it at the requested address
     *   - Wires its single IRQ to the provided qemu_irq
     *
     * serial_hd(0) returns the chardev attached to the first -serial
     * argument (e.g. stdio, tcp, file).  If -serial none was given this
     * is NULL and the UART will discard TX / produce no RX.
     */
    pl011_create(UGUR_M4_UART0_BASE,
                 qdev_get_gpio_in(nvic, UGUR_M4_UART_IRQ),
                 serial_hd(0));

    // 6. SP804 Dual Timer
    /*
     * The SP804 is ARM's "Dual Timer" — one device, two independent
    * down-counters, with one combined IRQ line in this QEMU model.
     *
    * SysBus IRQ layout (from hw/timer/arm_timer.c):
    *   irq[0]  → combined (OR of timer1 and timer2)
     */
    dev = qdev_new("sp804");
    /*
     * SP804 reference clock — 1 MHz gives convenient countdown periods
     * (LOAD = 999 999 → 1 s, LOAD = 999 → 1 ms, etc.).
     */
    qdev_prop_set_uint32(dev, "freq0", 1000000); /* timer 1: 1 MHz */
    qdev_prop_set_uint32(dev, "freq1", 1000000); /* timer 2: 1 MHz */
    sbd = SYS_BUS_DEVICE(dev);
    sysbus_realize_and_unref(sbd, &error_fatal);
    sysbus_mmio_map(sbd, 0, UGUR_M4_TIMER0_BASE);
    sysbus_connect_irq(sbd, 0, qdev_get_gpio_in(nvic, UGUR_M4_TIMER1_IRQ));
    /* combined interrupt line wired to NVIC IRQ 0 */

    // 7. PL061 GPIO
    /*
     * PL061 provides 8 independently-directable GPIO pins with
     * interrupt support (edge or level, per-pin).
     *
     * SysBus IRQ layout:
     *   irq[0]  → combined GPIO interrupt line
     */
    dev = qdev_new("pl061");
    sbd = SYS_BUS_DEVICE(dev);
    sysbus_realize_and_unref(sbd, &error_fatal);
    sysbus_mmio_map(sbd, 0, UGUR_M4_GPIO0_BASE);
    sysbus_connect_irq(sbd, 0, qdev_get_gpio_in(nvic, UGUR_M4_GPIO_IRQ));
    
    // 8. Create ugur-mmio-dev 
    dev = qdev_new(TYPE_UGUR_MMIO_DEV);
    sbd = SYS_BUS_DEVICE(dev);
    sysbus_realize_and_unref(sbd, &error_fatal);
    sysbus_mmio_map(sbd, 0, UGUR_MMIO_DEV_BASE);
    sysbus_connect_irq(sbd, 0, qdev_get_gpio_in(nvic, UGUR_MMIO_DEV_IRQ));


    // 9. Stub out the rest of the peripheral address space
    /*
     * Any guest access to an unimplemented region is logged as a
     * GUEST_ERROR (visible with -d guest_errors) rather than causing
     * a silent bus fault.
     */
    create_unimplemented_device("reserved", 0x40003000, 0x000FD000);

    // 10. Load firmware
    /*
     * arm_load_kernel() handles both ELF (-kernel) and raw binary
     * (-device loader,...) images.  The ARMv7-M CPU automatically reads
     * the initial SP and reset vector from the vector table at 0x0 after
     * the image is placed in Flash.
     */
    if (machine->kernel_filename) {
        s->bootinfo.board_id = -1;            /* no ATAG/DTB handoff     */
        s->bootinfo.loader_start = UGUR_M4_FLASH_BASE;
        s->bootinfo.ram_size = UGUR_M4_SRAM_SIZE;
        arm_load_kernel(ARM_CPU(first_cpu), machine, &s->bootinfo);
    }
}

// MachineClass initialization
static void ugur_m4_class_init(ObjectClass *oc, const void *data)
{
    MachineClass *mc = MACHINE_CLASS(oc);

    mc->desc             = "Ugur Cortex-M4 machine";
    mc->init             = ugur_m4_init;
    mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-m4");
    mc->default_ram_size = UGUR_M4_SRAM_SIZE;

    /* Cortex-M machines don't use PC-style peripherals */
    mc->no_floppy   = true;
    mc->no_cdrom    = true;
    mc->no_parallel = true;
}

static const TypeInfo ugur_m4_type = {
    .name          = TYPE_UGUR_M4_MACHINE,
    .parent        = TYPE_MACHINE,
    .instance_size = sizeof(UgurM4State),
    .class_init    = ugur_m4_class_init,
    .interfaces    = arm_machine_interfaces,
};

static void ugur_m4_register(void)
{
    type_register_static(&ugur_m4_type);
}
type_init(ugur_m4_register)
