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

# script for stm32h7rsx family

#
# stm32h7rs devices support both JTAG and SWD transports.
#
source [find target/swj-dp.tcl]
source [find mem_helper.tcl]

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

# Issue an error when hla is used
if { [using_hla] } {
	echo "Error : hla does not support STM32H7RS devices"
}

set _ENDIAN little

# Work-area is a space in RAM used for flash programming
# By default use 64kB
if { [info exists WORKAREASIZE] } {
   set _WORKAREASIZE $WORKAREASIZE
} else {
   set _WORKAREASIZE 0x10000
}

#jtag scan chain
if { [info exists CPUTAPID] } {
   set _CPUTAPID $CPUTAPID
} else {
   if { [using_jtag] } {
	  set _CPUTAPID 0x6ba00477
   } {
      set _CPUTAPID 0x6ba02477
   }
}

swj_newdap $_CHIPNAME cpu -irlen 4 -ircapture 0x1 -irmask 0xf -expected-id $_CPUTAPID
dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu

if {[using_jtag]} {
   jtag newtap $_CHIPNAME bs -irlen 5
}

target create $_CHIPNAME.ap0 mem_ap -dap $_CHIPNAME.dap -ap-num 0
target create $_CHIPNAME.cpu0 cortex_m -endian $_ENDIAN -dap $_CHIPNAME.dap -ap-num 1
# test ram area
$_CHIPNAME.cpu0 configure -work-area-phys 0x24000000 -work-area-size $_WORKAREASIZE -work-area-backup 0

flash bank $_CHIPNAME.flash stm32h7x 0x08000000 0 0 0 $_CHIPNAME.cpu0

# Make sure that cpu0 is selected
targets $_CHIPNAME.cpu0

# Clock after reset is HSI at 64 MHz, no need of PLL
adapter speed 4000

adapter srst delay 100
if {[using_jtag]} {
 jtag_ntrst_delay 100
}

# use hardware reset
#
# The STM32H7RS does not support connect_assert_srst mode because the AXI is
# unavailable while SRST is asserted, and that is used to access the DBGMCU
# component at 0x5C001000 in the examine-end event handler.
#
reset_config srst_gates_jtag

if {![using_hla]} {
   # if srst is not fitted use SYSRESETREQ to
   # perform a soft reset
	$_CHIPNAME.cpu0 cortex_m reset_config sysresetreq

   # Set CSW[27], which according to ARM ADI v5 appendix E1.4 maps to AHB signal
   # HPROT[3], which according to AMBA AHB/ASB/APB specification chapter 3.7.3
   # makes the data access cacheable. This allows reading and writing data in the
   # CPU cache from the debugger, which is far more useful than going straight to
   # RAM when operating on typical variables, and is generally no worse when
   # operating on special memory locations.
   $_CHIPNAME.dap apcsw 0x08000000 0x08000000
}

$_CHIPNAME.cpu0 configure -event examine-end {
	# Enable debug during low power modes (uses more power)
	# DBGMCU_CR |= DBG_STANDBY | DBG_STOP | DBG_SLEEP
	mmw 0x5C001004 0x00000007 0

	# Enable clock for tracing
	# DBGMCU_CR |= TRACECLKEN
	mmw 0x5C001004 0x00100000 0
}
