if {[info exists ::env(SWDIF)]} {
    if {$::env(SWDIF) eq "JLINK"} {
	puts "Using JLINK"
	source [find atm_jlink.tcl]
    } else {
	error [format "Unknown SWDIF=%s setting" $::env(SWDIF)]
    }
} else {
    puts "Using FTDI"
    source [find atm_ftdi.tcl]
}

source [find target/swj-dp.tcl]

set _CHIPNAME Sydney
set _ENDIAN little
# JTAG IDCODE register
set _CPUTAPID 0x0BA01477

swj_newdap $_CHIPNAME cpu -expected-id $_CPUTAPID -irlen 4

set _TARGETNAME $_CHIPNAME.cpu
dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu
target create $_TARGETNAME cortex_m -dap $_CHIPNAME.dap
$_TARGETNAME configure -work-area-backup 1 -work-area-phys 0x20010000 -work-area-size 128

set _RESET_HARD_ON_EXIT 0
set _RESET_HARD_TIME 2000
if {[info exists ::env(FTDI_RESET_HARD_TIME)]} {
    set _RESET_HARD_TIME $::env(FTDI_RESET_HARD_TIME)
    puts "_RESET_HARD_TIME set to $_RESET_HARD_TIME"
}
rename exit orig_exit
proc exit {} {
    global _CHIPNAME
    global _RESET_HARD_ON_EXIT
    global _RESET_HARD_TIME
    poll off
    # Deassert syspwrupreq and dbgpwrupreq
    $_CHIPNAME.dap dpreg 4 0x00000041
    if {$_RESET_HARD_ON_EXIT} {
	assert_pwd
	sleep $_RESET_HARD_TIME
	release_reset
    }
    orig_exit
}

reset_config none
cortex_m reset_config sysresetreq

proc release_reset {} {
    deassert_pwd
}

proc reset_hard [list [list reset_time $_RESET_HARD_TIME] ] {
    poll off
    assert_pwd
    sleep $reset_time
    release_reset
    sleep 100
    poll on
}

proc set_benign_boot {} {
    assert_bboot
}

proc set_normal_boot {} {
    deassert_bboot
}

proc polloff_n_reset_hard {} {
    global _RESET_HARD_TIME
    global _CHIPNAME
    poll off
    $_CHIPNAME.dap dpreg 4 0x00000041
    assert_pwd
    sleep $_RESET_HARD_TIME
    release_reset
}

# Tested as high as 20000, but openocd complains a lot when the
# AHB bus is busy (ex: when running from flash)
set _SWD_KHZ [expr {[info exists ::env(SYDNEY_SWD_KHZ)] ? $::env(SYDNEY_SWD_KHZ) : 1000}]
adapter_khz $_SWD_KHZ

gdb_port disabled
telnet_port disabled
tcl_port disabled

source [find atm2x_top.tcl]
source [find atm2x_coredump.tcl]
