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

set _USER1 0x02

if { [info exists JTAGSPI_IR] } {
	set _JTAGSPI_IR $JTAGSPI_IR
} elseif {[info exists JTAGSPI_CHAIN_ID]} {
	set _JTAGSPI_CHAIN_ID $JTAGSPI_CHAIN_ID
} else {
	set _JTAGSPI_IR $_USER1
}

if { [info exists TARGETNAME] } {
	set _TARGETNAME $TARGETNAME
} else {
	set _TARGETNAME $_CHIPNAME.proxy
}

if { [info exists FLASHNAME] } {
	set _FLASHNAME $FLASHNAME
} else {
	set _FLASHNAME $_CHIPNAME.spi
}

target create $_TARGETNAME testee -chain-position $_CHIPNAME.tap
if { [info exists _JTAGSPI_IR] } {
	flash bank $_FLASHNAME jtagspi 0 0 0 0 $_TARGETNAME $_JTAGSPI_IR
} else {
    flash bank $_FLASHNAME jtagspi 0 0 0 0 $_TARGETNAME -pld $_JTAGSPI_CHAIN_ID
}

# initialize jtagspi flash
# chain_id: identifier of pld (you can get a list with 'pld devices')
# proxy_bit: file with bitstream connecting JTAG and SPI interface in the PLD.
# release_from_pwr_down_cmd: optional, command sent to spi flash before probing.
#                            ex: 0xAB to release from power-dowm.
#                            Just omit it to not send a command.

proc jtagspi_init {chain_id proxy_bit {release_from_pwr_down_cmd -1}} {
	# load proxy bitstream $proxy_bit and probe spi flash
	global _FLASHNAME
	if { $proxy_bit ne "" } {
		pld load $chain_id $proxy_bit
	}
	reset halt
	if {$release_from_pwr_down_cmd != -1} {
		jtagspi cmd $_FLASHNAME 0 $release_from_pwr_down_cmd
	}
	flash probe $_FLASHNAME
}

proc jtagspi_program {bin addr} {
	# write and verify binary file $bin at offset $addr
	global _FLASHNAME
	flash write_image erase $bin $addr
	flash verify_bank $_FLASHNAME $bin $addr
}
