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

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

source [find target/stm32x5x_common.cfg]

# In order to allow the flash program and erase operations,
# we need to set the voltage scale to range 1

proc config_voltage_range {} {
    set offset [expr {[stm32x5x_is_secure] ? 0x10000000 : 0}]
    # PWR voltage scaling register
    set PWR_VOSR [expr {0x4003080C + $offset}]
    # PWR supply voltage monitoring control register
    set PWR_SVMCR [expr {0x40030810 + $offset}]
    # RCC AHB1 peripheral clock enable register 2
    # RCC_AHB1ENR2 = PWREN
    mww [expr {0x40030C94 + $offset}] 0x4
    if {(([mrw $PWR_VOSR] & 0x10001) != 0x10001)} {
        # PWR_SVMCR = IO2SV
        mmw $PWR_SVMCR 0x20000000 0
        # PWR_VOSR : R1EN: Voltage scaling range 1
        mmw $PWR_VOSR 1 3
        # while !(PWR_VOSR & R1RDY)
        while {([mrw $PWR_VOSR] & 0x10001) != 0x10001} {}
        # Enable EPOD Booster
	    mmw $PWR_VOSR 0x00000100 0
        # while !(PWR_VOSR & BOOSTRDY)
        while {([mrw $PWR_VOSR] & 0x1000000) != 0} {}
	}
}

$_TARGETNAME configure -event reset-init {
	config_voltage_range
}
