>From b8bf5b49bc090e0710c4785d7b736d471c2c43d7 Mon Sep 17 00:00:00 2001
From: Bruno FLEURETTE <bruno.fleurette@gmail.com>
Date: Tue, 10 Jan 2012 13:37:53 +0100
Subject: [PATCH] Signed-off-by: Bruno FLEURETTE <bruno.fleurette@gmail.com>

STM32F2x: pre-check flash unlock

add checking of the current flash lock status before performing the unlock sequence (which would fail in an unlocked state)

Change-Id: I6a1431da6f6ebf008ff4948a2df266c80296eaea
---
 src/flash/nor/stm32f2x.c |   12 +++++++++++-
 1 files changed, 11 insertions(+), 1 deletions(-)

diff --git a/src/flash/nor/stm32f2x.c b/src/flash/nor/stm32f2x.c
index 479df8a..591b326 100644
--- a/src/flash/nor/stm32f2x.c
+++ b/src/flash/nor/stm32f2x.c
@@ -234,8 +234,18 @@ static int stm32x_unlock_reg(struct target *target)
 {
 	uint32_t ctrl;
 
+	/* first check if not already unlocked
+	 * otherwise writing on STM32_FLASH_KEYR will fail
+	 */
+	int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
+	if (retval != ERROR_OK)
+		return retval;
+
+	if ((ctrl & FLASH_LOCK) == 0)
+		return ERROR_OK;
+
 	/* unlock flash registers */
-	int retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
+	retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
 	if (retval != ERROR_OK)
 		return retval;
 
-- 
1.7.4.4

