# script for AT32f4xx family

#
# AT32 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 at32f4xx
}

if { [info exists ENDIAN] } {
   set _ENDIAN $ENDIAN
} else {
   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 0x1000
}

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

# Allow overriding the Flash bank size
if { [info exists FLASH_SIZE] } {
    set _FLASH_SIZE $FLASH_SIZE
} else {
    # autodetect size
    set _FLASH_SIZE 0
}


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

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

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

# flash size will be probed
set _FLASHNAME $_CHIPNAME.bank1
flash bank $_FLASHNAME $_CHIPNAME 0x08000000 0 0 0 $_TARGETNAME
set _FLASHNAME $_CHIPNAME.bank2
flash bank $_FLASHNAME $_CHIPNAME 0x08080000 0 0 0 $_TARGETNAME

#spim config
#spim iomux param 
set spim_iomux 0x1
#spim flash type
set spim_type 0x1
#spim flash size(16Mbyte)
set spim_size 0x1000000
set _FLASHNAME $_CHIPNAME.spim
flash bank $_FLASHNAME $_CHIPNAME 0x08400000 0 0 0 $_TARGETNAME $spim_iomux $spim_type $spim_size


# JTAG speed should be <= F_CPU/6. F_CPU after reset is 8MHz, so use F_JTAG = 1MHz
adapter speed 5000

adapter srst delay 100

reset_config srst_nogate

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

$_TARGETNAME configure -event examine-end {
	# DBGMCU_CR |= DBG_WWDG_STOP | DBG_IWDG_STOP |
	#              DBG_STANDBY | DBG_STOP | DBG_SLEEP
	mmw 0xE0042004 0x00000307 0
}

$_TARGETNAME configure -event trace-config {
	# Set TRACE_IOEN; TRACE_MODE is set to async; when using sync
	# change this value accordingly to configure trace pins
	# assignment
	mmw 0xE0042004 0x00000020 0
}

$_TARGETNAME configure -event reset-init {
	mww 0x40021030 0x02000000
	mww 0x40021054 0x0000020d
	sleep 1
}
