# SPDX-License-Identifier: GPL-2.0-or-later

#
# RSL10: ARM Cortex-M3
#

source [find target/swj-dp.tcl]

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

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

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

swj_newdap $_CHIPNAME cpu -expected-id $_CPUTAPID
dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu

set _TARGETNAME $_CHIPNAME.cpu
target create $_TARGETNAME cortex_m -dap $_CHIPNAME.dap

$_TARGETNAME configure -work-area-phys 0x200000 -work-area-size $_WORKAREASIZE -work-area-backup 0

# TODO: configure reset
# reset_config srst_only srst_nogate connect_assert_srst

$_TARGETNAME configure -event examine-fail rsl10_lock_warning

proc rsl10_check_connection {} {
    set target [target current]
    set dap [$target cget -dap]

	set IDR [$dap apreg 0 0xfc]
	if {$IDR != 0x24770011} {
		echo "Error: Cannot access RSL10 AP, maybe connection problem!"
		return 1
	}
    return 0
}

proc rsl10_lock_warning {} {
    if {[rsl10_check_connection]} {return}

    poll off
    echo "****** WARNING ******"
    echo "RSL10 device probably has lock engaged."
    echo "Debug access is denied."
    echo "Use 'rsl10 unlock key1 key2 key3 key4' to erase and unlock the device."
    echo "****** ....... ******"
    echo ""
}

flash bank $_CHIPNAME.main rsl10 0x00100000 0x60000 0 0 $_TARGETNAME
flash bank $_CHIPNAME.nvr1 rsl10 0x00080000 0x800 0 0 $_TARGETNAME
flash bank $_CHIPNAME.nvr2 rsl10 0x00080800 0x800 0 0 $_TARGETNAME
flash bank $_CHIPNAME.nvr3 rsl10 0x00081000 0x800 0 0 $_TARGETNAME

# TODO: implement flashing for nvr4
# flash bank $_CHIPNAME.nvr4 rsl10 0x00081800 0x400 0 0 $_TARGETNAME
