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

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

source [find target/stm32x5x_common.cfg]

proc stm32l5x_clock_config {} {
	set offset [expr {[stm32x5x_is_secure] ? 0x10000000 : 0}]
	# MCU clock is MSI (4MHz) after reset, set MCU freq at 110 MHz with PLL
	# RCC_APB1ENR1 = PWREN
	mww [expr {0x40021058 + $offset}] 0x10000000
	# delay for register clock enable (read back reg)
	mrw [expr {0x40021058 + $offset}]
	# PWR_CR1 : VOS Range 0
	mww [expr {0x40007000 + $offset}] 0
	# while (PWR_SR2 & VOSF)
	while {([mrw [expr {0x40007014 + $offset}]] & 0x0400)} {}
	# FLASH_ACR : 5 WS for 110 MHz HCLK
	mww 0x40022000 0x00000005
	# RCC_PLLCFGR = PLLP=PLLQ=0, PLLR=00=2, PLLREN=1, PLLN=55, PLLM=0000=1, PLLSRC=MSI 4MHz
	# fVCO = 4 x 55 /1 = 220
	# SYSCLOCK = fVCO/PLLR = 220/2 = 110 MHz
	mww [expr {0x4002100C + $offset}] 0x01003711
	# RCC_CR |= PLLON
	mmw [expr {0x40021000 + $offset}] 0x01000000 0
	# while !(RCC_CR & PLLRDY)
	while {!([mrw [expr {0x40021000 + $offset}]] & 0x02000000)} {}
	# RCC_CFGR |= SW_PLL
	mmw [expr {0x40021008 + $offset}] 0x00000003 0
	# while ((RCC_CFGR & SWS) != PLL)
	while {([mrw [expr {0x40021008 + $offset}]] & 0x0C) != 0x0C} {}
}

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