# Copyright (c) 2022-2025 ATL Electronics
#
# SPDX-License-Identifier: Apache-2.0

if { [info exists CHIPNAME] } {
    set _CHIPNAME $CHIPNAME
} else {
    set _CHIPNAME riscv
}

if { [info exists WORKAREASIZE] } {
    set _WORKAREASIZE $WORKAREASIZE
} else {
    set _WORKAREASIZE 0x10000
}

if { [info exists WORKAREAADDR] } {
    set _WORKAREAADDR $WORKAREAADDR
} else {
    set _WORKAREAADDR 0x22020000
}

if { [info exists CPUTAPID] } {
    set _CPUTAPID $CPUTAPID
} else {
    set _CPUTAPID 0x20000c05
}

transport select jtag
jtag newtap $_CHIPNAME cpu -irlen 5 -expected-id $_CPUTAPID

set _TARGETNAME $_CHIPNAME.cpu
target create $_TARGETNAME.0 riscv -chain-position $_TARGETNAME

$_TARGETNAME.0 configure -work-area-phys $_WORKAREAADDR -work-area-size $_WORKAREASIZE -work-area-backup 1

echo "Ready for Remote Connections"

$_TARGETNAME.0 configure -event reset-assert-pre {
    echo "reset-assert-pre"
    adapter speed 100
}

$_TARGETNAME.0 configure -event reset-deassert-post {
    echo "reset-deassert-post"

    adapter speed 100

    reg mstatus 0x7800
    reg mie 0x0
#    reg pc 0x23000000
}

$_TARGETNAME.0 configure -event reset-init {
    echo "reset-init"

    adapter speed 3000
}

$_TARGETNAME.0 configure -event gdb-attach {
        echo "Debugger attaching: halting execution"
        reset halt
        gdb_breakpoint_override hard
}

$_TARGETNAME.0 configure -event gdb-detach {
        echo "Debugger detaching: resuming execution"
        resume
}

gdb_memory_map enable
gdb_flash_program enable

# 'progbuf', 'sysbus' or 'abstract'
riscv set_mem_access sysbus
riscv set_command_timeout_sec 1

init
reset init
