/*
 * demo.c — Bare-metal demo for the custom Cortex-M4 QEMU machine.
 *
 * Exercises:
 *   • PL011 UART  — polled TX, interrupt-driven RX echo
 *   • SP804 Timer — periodic interrupt at 1 Hz
 *   • PL061 GPIO  — pin 0 toggled on every timer tick
 *
 * Build
 * -----
 *   arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -nostartfiles \
 *       -T linker.ld -O2 -o firmware.elf startup.s demo.c
 *
 * Run
 * ---
 *   qemu-system-arm -M my-machine -kernel firmware.elf \
 *       -serial stdio -nographic
 */

#include <stdint.h>
#include <stdbool.h>

/* ─── Base addresses (must match my_machine.c) ──────────────────── */
#define UART0_BASE    0x40000000U
#define TIMER0_BASE   0x40001000U
#define GPIO0_BASE    0x40002000U
#define NVIC_BASE     0xE000E100U   /* NVIC ISER0 */

/* ─── PL011 UART registers ─────────────────────────────────────────
 * Reference: ARM DDI0183G — PrimeCell UART (PL011)
 */
#define UART_DR(b)     (*(volatile uint32_t *)((b) + 0x000))
#define UART_FR(b)     (*(volatile uint32_t *)((b) + 0x018))  /* Flag reg  */
#define UART_IBRD(b)   (*(volatile uint32_t *)((b) + 0x024))  /* Baud int  */
#define UART_FBRD(b)   (*(volatile uint32_t *)((b) + 0x028))  /* Baud frac */
#define UART_LCR_H(b)  (*(volatile uint32_t *)((b) + 0x02C))  /* Line ctrl */
#define UART_CR(b)     (*(volatile uint32_t *)((b) + 0x030))  /* Control   */
#define UART_IMSC(b)   (*(volatile uint32_t *)((b) + 0x038))  /* IRQ mask  */
#define UART_ICR(b)    (*(volatile uint32_t *)((b) + 0x044))  /* IRQ clear */

#define UART_FR_TXFF   (1u << 5)   /* TX FIFO full  */
#define UART_FR_RXFE   (1u << 4)   /* RX FIFO empty */
#define UART_CR_UARTEN (1u << 0)
#define UART_CR_TXE    (1u << 8)
#define UART_CR_RXE    (1u << 9)
#define UART_LCR_FEN   (1u << 4)   /* FIFO enable   */
#define UART_LCR_8N1   (0x3u << 5) /* 8-bit, no parity, 1 stop */
#define UART_IMSC_RX   (1u << 4)   /* RX interrupt mask bit */

/* ─── SP804 Dual Timer registers ──────────────────────────────────
 * Reference: ARM DDI0271D — SP804 Dual-Timer Module
 * Two identical blocks: Timer1 at +0x00, Timer2 at +0x20
 */
#define SP804_T1LOAD(b)   (*(volatile uint32_t *)((b) + 0x000))
#define SP804_T1VALUE(b)  (*(volatile uint32_t *)((b) + 0x004))
#define SP804_T1CTRL(b)   (*(volatile uint32_t *)((b) + 0x008))
#define SP804_T1INTCLR(b) (*(volatile uint32_t *)((b) + 0x00C))
#define SP804_T1MIS(b)    (*(volatile uint32_t *)((b) + 0x014))

/* CTRL bits */
#define SP804_CTRL_EN      (1u << 7)
#define SP804_CTRL_PERIODIC (1u << 6)
#define SP804_CTRL_IE      (1u << 5)
#define SP804_CTRL_32BIT   (1u << 1)   /* 0=16-bit, 1=32-bit counter */
#define SP804_CTRL_ONESHOT (1u << 0)

/* ─── PL061 GPIO registers ─────────────────────────────────────────
 * Reference: ARM DDI0190B — PL061 General-Purpose I/O
 * DATA is accessed via address-bit masking: bits [9:2] = pin mask.
 * Writing GPIODATA[pin_mask] only affects the masked pins.
 */
#define PL061_DATA(b, mask) \
    (*(volatile uint32_t *)((b) + ((mask) << 2)))
#define PL061_DIR(b)        (*(volatile uint32_t *)((b) + 0x400))
#define PL061_IS(b)         (*(volatile uint32_t *)((b) + 0x404))
#define PL061_IBE(b)        (*(volatile uint32_t *)((b) + 0x408))
#define PL061_IEV(b)        (*(volatile uint32_t *)((b) + 0x40C))
#define PL061_IE(b)         (*(volatile uint32_t *)((b) + 0x410))
#define PL061_MIS(b)        (*(volatile uint32_t *)((b) + 0x418))
#define PL061_IC(b)         (*(volatile uint32_t *)((b) + 0x41C))

/* ─── NVIC helpers (Cortex-M4 core peripheral) ────────────────────
 *
 * NVIC_BASE = 0xE000E100  (ISER0 address)
 *
 *  Register       Offset from NVIC_BASE   Absolute
 *  ISER0/1        +0x000 / +0x004         0xE000E100 / E104
 *  ICER0/1        +0x080 / +0x084         0xE000E180 / E184
 *  ISPR0/1        +0x100 / +0x104         0xE000E200 / E204
 *  ICPR0/1        +0x180 / +0x184         0xE000E280 / E284
 */
#define NVIC_ISERn(n) (*(volatile uint32_t *)(NVIC_BASE + 0x000 + 4u * (n)))
#define NVIC_ICPRn(n) (*(volatile uint32_t *)(NVIC_BASE + 0x180 + 4u * (n)))

static inline void nvic_irq_enable(unsigned irq)
{
    NVIC_ISERn(irq / 32u) |= (1u << (irq % 32u));
}
static inline void nvic_irq_clear(unsigned irq)
{
    NVIC_ICPRn(irq / 32u)  = (1u << (irq % 32u));
}

/* ─── UART init & helpers ─────────────────────────────────────────
 *
 * In QEMU's PL011 model the baud-rate divisor registers are accepted
 * but don't actually control timing — any value works.  We program
 * 115200 baud from a 24 MHz UART clock for documentation completeness:
 *   IBRD = 24_000_000 / (16 * 115200) = 13
 *   FBRD = round(0.02 * 64) = 1
 */
static void uart_init(void)
{
    UART_CR(UART0_BASE)    = 0;              /* disable while configuring   */
    UART_IBRD(UART0_BASE)  = 13;
    UART_FBRD(UART0_BASE)  = 1;
    UART_LCR_H(UART0_BASE) = UART_LCR_8N1 | UART_LCR_FEN;
    UART_IMSC(UART0_BASE)  = UART_IMSC_RX;  /* enable RX interrupt         */
    UART_CR(UART0_BASE)    = UART_CR_UARTEN | UART_CR_TXE | UART_CR_RXE;
}

static void uart_putc(char c)
{
    while (UART_FR(UART0_BASE) & UART_FR_TXFF) { /* spin while TX FIFO full */ }
    UART_DR(UART0_BASE) = (uint32_t)(uint8_t)c;
}

static void uart_puts(const char *s)
{
    for (; *s; s++) {
        if (*s == '\n') uart_putc('\r');
        uart_putc(*s);
    }
}

static void uart_putnum(unsigned num)
{
    char buf[11];  /* enough for 32-bit unsigned int in decimal + null */
    char *p = buf + sizeof(buf) - 1;
    *p = '\0';
    do {
        p--;
        *p = '0' + (num % 10);
        num /= 10;
    } while (num > 0);
    uart_puts(p);
}

/* ─── SP804 Timer 1 — 1 Hz periodic ─────────────────────────────
 *
 * freq-hz is set to 1 MHz in my_machine.c.
 * LOAD = 1_000_000 - 1 → fires every 1 000 000 ticks = 1 second.
 */
static void timer_init_1hz(void)
{
    SP804_T1CTRL(TIMER0_BASE)  = 0;                 /* disable first        */
    SP804_T1LOAD(TIMER0_BASE)  = 1000000U - 1U;     /* 1 s at 1 MHz         */
    SP804_T1INTCLR(TIMER0_BASE) = 1;                /* clear any old IRQ    */
    SP804_T1CTRL(TIMER0_BASE)  = SP804_CTRL_EN
                                | SP804_CTRL_PERIODIC
                                | SP804_CTRL_IE
                                | SP804_CTRL_32BIT;
}

/* ─── PL061 GPIO — pin 0 as output ─────────────────────────────── */
static void gpio_init(void)
{
    PL061_DIR(GPIO0_BASE) |= (1u << 0);   /* pin 0 → output */
}

static void gpio_toggle_pin0(void)
{
    static bool state = false;
    state = !state;
    /* PL061 address-bit masking: bit 2 in address = pin 0 mask bit */
    PL061_DATA(GPIO0_BASE, 1u << 0) = state ? (1u << 0) : 0u;
}

/* ─── Interrupt handlers ─────────────────────────────────────────
 *
 * Names must match the vector table entries in startup.s.
 */
volatile int tick_count = 0;  /* incremented on every timer tick */
/* IRQ 28 → SP804 Timer 1  (TIM2_IRQHandler in STM32F407 vector table) */
void TIM2_IRQHandler(void)
{
    tick_count++;
    SP804_T1INTCLR(TIMER0_BASE) = 1;   /* acknowledge SP804 interrupt     */
    nvic_irq_clear(28);

    gpio_toggle_pin0();
    
    uart_puts("tick : ");
    uart_putnum(tick_count);
    uart_puts("\n");
}

/* IRQ 37 → PL011 UART RX  (USART1_IRQHandler in STM32F407 vector table) */
void USART1_IRQHandler(void)
{
    /* Read all available RX bytes and echo them back */
    while (!(UART_FR(UART0_BASE) & UART_FR_RXFE)) {
        uint8_t ch = (uint8_t)UART_DR(UART0_BASE);
        UART_DR(UART0_BASE) = ch;   /* echo */
    }
    UART_ICR(UART0_BASE) = UART_IMSC_RX;   /* clear RX interrupt           */
    nvic_irq_clear(37);
}

/* ─── main ──────────────────────────────────────────────────────── */
int main(void)
{
    uart_init();
    uart_puts("=== Custom Cortex-M4 QEMU Machine ===\n");
    uart_puts("Peripherals: PL011 UART | SP804 Timer | PL061 GPIO\n\n");

    gpio_init();
    timer_init_1hz();

    /* Enable IRQs in the NVIC */
    nvic_irq_enable(28);  /* SP804 Timer 1 → TIM2_IRQHandler  */
    nvic_irq_enable(37);  /* PL011 UART    → USART1_IRQHandler */

    /* Unmask CPU interrupts */
    __asm volatile ("cpsie i" ::: "memory");

    uart_puts("Timer started. You should see 'tick' every second.\n");
    uart_puts("Type anything to echo it back via UART RX interrupt.\n\n");

    for (;;) {
        __asm volatile ("wfi");   /* sleep until next interrupt */
    }
}
