# Renesas R-Car Gen3 H3 Salvator-X Cortex-R7 Board Config

source [find interface/ftdi/olimex-arm-usb-ocd-h.cfg]
source [find target/renesas_rcar_reset_common.cfg]
set _CHIPNAME r8a77951
set DAP_TAPID 0x5ba00477
set CA57_0_DBGBASE 0x80410000
set CA57_0_CTIBASE 0x80420000
set CR7_DBGBASE 0x80910000
set CR7_CTIBASE 0x80918000

adapter srst delay 1000
adapter speed 20000
global $_CHIPNAME
transport select jtag

jtag newtap $_CHIPNAME cpu -irlen 4 -ircapture 0x01 -irmask 0x0f -expected-id $DAP_TAPID
dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu

cti create $_CHIPNAME.r7.cti -dap $_CHIPNAME.dap -ap-num 1 -baseaddr $CR7_CTIBASE
target create $_CHIPNAME.r7 cortex_r4 -dap $_CHIPNAME.dap -ap-num 1 -dbgbase $CR7_DBGBASE -defer-examine

$_CHIPNAME.r7 configure -rtos auto

cti create $_CHIPNAME.a57.0.cti -dap $_CHIPNAME.dap -ap-num 1 -baseaddr $CA57_0_CTIBASE
target create $_CHIPNAME.a57.0 aarch64 -dap $_CHIPNAME.dap -ap-num 1 -dbgbase $CA57_0_DBGBASE -cti $_CHIPNAME.a57.0.cti

proc reset_cr7 { assert } {
    global _CHIPNAME
    if { $assert == 1 } {
	# Software Reset Register 2 Bit(22) Arm Realtime core
	$_CHIPNAME.a57.0 mww 0xe61500b0 0x00400000
    } else {
	# Software Reset Clearing Register 2 Bit(22) Arm Realtime core
	$_CHIPNAME.a57.0 mww 0xe6150948 0x00400000
    }
}

# This function make use of A5x processor to:
# - Power on the CR7 (PWRONCR7)
# - Set the boot address (CR7BAR)
# - Halt the processor
# - Deassert the CR7 reset
proc start_cr7 { args } {
    global _CHIPNAME

    targets $_CHIPNAME.a57.0
    $_CHIPNAME.a57.0 arp_halt

    # CR7BAR RBAR [31:18] BAREN bit(4)
    $_CHIPNAME.a57.0 mww 0xe6160070 0x40040010

    # PWRONCR7
    $_CHIPNAME.a57.0 mww 0xe618024c 1
    # Wait until power is on. Also possible to
    # poll PWRSR7 and CR7PSTR register.
    sleep 100

    $_CHIPNAME.r7 arp_examine
    catch { $_CHIPNAME.r7 arp_halt }
    reset_cr7 0

    # resume a5x processor or cmt timer will not run
    resume
    # set CR7 processor as default target for future commands
    targets $_CHIPNAME.r7
}

$_CHIPNAME.r7 configure -event reset-end {
     global _CHIPNAME
     targets $_CHIPNAME.a57.0
     # Resume the A57 processor and gives
     # enough time to A57 bootloaders to set-up dram
     # clocks, power management, security groups
     resume
     sleep 500
     $_CHIPNAME.a57.0 arp_halt
     $_CHIPNAME.a57.0 arp_poll
     start_cr7
}

$_CHIPNAME.a57.0 configure -event examine-end {
     start_cr7
}

$_CHIPNAME.r7 configure -event gdb-attach {
     reset halt
}
