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

# script for stm32u5x family
# stm32u5x 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 stm32u5x
}

source [find target/stm32x5x_common.cfg]

proc stm32u5x_clock_config {} {
	set offset [expr {[stm32x5x_is_secure] ? 0x10000000 : 0}]
	# MCU clock is at MSI 4MHz after reset, set MCU freq at 160 MHz with PLL

	# Enable voltage range 1 for frequency above 100 Mhz
	# RCC_AHB3ENR = PWREN
	mww [expr {0x46020C94 + $offset}] 0x00000004
	# delay for register clock enable (read back reg)
	mrw [expr {0x46020C94 + $offset}]
	# PWR_VOSR : VOS Range 1
	mmw [expr {0x4602080C + $offset}] 0x00030000 0
	# while !(PWR_VOSR & VOSRDY)
	while {!([mrw [expr {0x4602080C + $offset}]] & 0x00008000)} {}
	# FLASH_ACR : 4 WS for 160 MHz HCLK
	mww [expr {0x40022000 + $offset}] 0x00000004
	# RCC_PLL1CFGR => PLL1MBOOST=0, PLL1M=0=/1, PLL1FRACEN=0, PLL1SRC=MSI 4MHz
	#                 PLL1REN=1, PLL1RGE => VCOInputRange=PLLInputRange_4_8
	mww [expr {0x46020C28 + $offset}] 0x00040009
	# Enable EPOD Booster
	mmw [expr {0x4602080C + $offset}] 0x00040000 0
	# while !(PWR_VOSR & BOOSTRDY)
	while {!([mrw [expr {0x4602080C + $offset}]] & 0x00004000)} {}
	# RCC_PLL1DIVR => PLL1P=PLL1Q=PLL1R=000001=/2, PLL1N=0x4F=80
	# fVCO = 4 x 80 /1 = 320
	# SYSCLOCK = fVCO/PLL1R = 320/2 = 160 MHz
	mww [expr {0x46020C34 + $offset}] 0x0101024F
	# RCC_CR |= PLL1ON
	mmw [expr {0x46020C00 + $offset}] 0x01000000 0
	# while !(RCC_CR & PLL1RDY)
	while {!([mrw [expr {0x46020C00 + $offset}]] & 0x02000000)} {}
	# RCC_CFGR1 |= SW_PLL
	mmw [expr {0x46020C1C + $offset}] 0x00000003 0
	# while ((RCC_CFGR1 & SWS) != PLL)
	while {([mrw [expr {0x46020C1C + $offset}]] & 0x0C) != 0x0C} {}
}

$_TARGETNAME configure -event reset-init {
	stm32u5x_clock_config
	# Boost JTAG frequency
	adapter speed 4000
}
