- // Read the RDP byte and check if it is 0xAA
- uint8_t rdp;
- retval = target_read_u32(target, FLASH_OBR, ®32);
- if (retval != ERROR_OK)
- return retval;
- rdp = reg32 & 0xFF;
- if (rdp != 0xAA)
- {
- /*
- * Unlocking the option byte is done by unlocking the PECR, then
- * by writing the 2 option byte keys to OPTKEYR
+ /* Get the flash size from target. 0x427 and 0x436 devices use a
+ * different location for the Flash Size register, please see RM0038 r8 or
+ * newer. */
+ if ((device_id & 0xfff) == 0x427 || (device_id & 0xfff) == 0x436)
+ retval = target_read_u16(target, F_SIZE_MP, &flash_size_in_kb);
+ else
+ retval = target_read_u16(target, F_SIZE, &flash_size_in_kb);
+
+ /* 0x436 devices report their flash size as a 0 or 1 code indicating 384K
+ * or 256K, respectively. Please see RM0038 r8 or newer and refer to
+ * section 30.1.1. */
+ if (retval == ERROR_OK && (device_id & 0xfff) == 0x436) {
+ if (flash_size_in_kb == 0)
+ flash_size_in_kb = 384;
+ else if (flash_size_in_kb == 1)
+ flash_size_in_kb = 256;
+ }
+
+ /* Failed reading flash size or flash size invalid (early silicon),
+ * default to max target family */
+ if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
+ LOG_WARNING("STM32L flash size failed, probe inaccurate - assuming %dk flash",
+ max_flash_size_in_kb);
+ flash_size_in_kb = max_flash_size_in_kb;
+ } else if (flash_size_in_kb > max_flash_size_in_kb) {
+ LOG_WARNING("STM32L probed flash size assumed incorrect since FLASH_SIZE=%dk > %dk, - assuming %dk flash",
+ flash_size_in_kb, max_flash_size_in_kb, max_flash_size_in_kb);
+ flash_size_in_kb = max_flash_size_in_kb;
+ }
+
+ if (stm32lx_info->has_dual_banks) {
+ /* Use the configured base address to determine if this is the first or second flash bank.
+ * Verify that the base address is reasonably correct and determine the flash bank size