# EP04 CVE2 peripheral bus firmware.
# CVE2 forces mtvec.MODE=1; exception vector is at 0x100.

    .option norvc

    .section .text.start, "ax"
    .globl _start
_start:
    la      sp, _stack_top
    la      t0, _bss_start
    la      t1, _bss_end
1:
    bgeu    t0, t1, 2f
    sw      zero, 0(t0)
    addi    t0, t0, 4
    j       1b
2:
    la      t0, trap_vector
    csrw    mtvec, t0
    call    main
3:
    j       3b

    .section .trap_vector, "ax"
    .balign 4
    .globl trap_vector
trap_vector:
    j       trap_handler          # exception entry (base + 0)
    .space  40                    # vectors 1..10 (unused)
    j       trap_handler          # external interrupt, cause 11 -> common prologue
    .space  204                   # vectors 12..31

    .section .text, "ax"
    .option norvc

# Trap handler: exceptions record mcause/mepc and skip the instruction;
# external interrupts clear the bus IRQ source and return without skipping.
trap_handler:
    addi    sp, sp, -16
    sw      t0, 0(sp)
    sw      t1, 4(sp)
    sw      t2, 8(sp)
    sw      t3, 12(sp)

    csrr    t0, mcause
    srli    t1, t0, 31
    bnez    t1, irq_handler

    la      t1, g_trap_cause
    sw      t0, 0(t1)
    csrr    t0, mepc
    la      t1, g_trap_epc
    sw      t0, 0(t1)
    la      t1, g_trap_count
    lw      t0, 0(t1)
    addi    t0, t0, 1
    sw      t0, 0(t1)
    csrr    t0, mepc
    addi    t0, t0, 4
    csrw    mepc, t0
    j       trap_return

irq_handler:
    la      t1, g_last_irq
    sw      t0, 0(t1)
    la      t1, g_irq_count
    lw      t0, 0(t1)
    addi    t0, t0, 1
    sw      t0, 0(t1)
    li      t1, 0x4004001c
    li      t2, 0x0000001f
    sw      t2, 0(t1)

trap_return:
    lw      t0, 0(sp)
    lw      t1, 4(sp)
    lw      t2, 8(sp)
    lw      t3, 12(sp)
    addi    sp, sp, 16
    mret
