]> git.sur5r.net Git - openocd/blob - src/flash/nor/stm32lx.c
Fix flash writing on stm32l0
[openocd] / src / flash / nor / stm32lx.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2011 by Clement Burin des Roziers                       *
9  *   clement.burin-des-roziers@hikob.com                                   *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
23  ***************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include "imp.h"
30 #include <helper/binarybuffer.h>
31 #include <target/algorithm.h>
32 #include <target/armv7m.h>
33 #include <target/cortex_m.h>
34
35 /* stm32lx flash register locations */
36
37 #define FLASH_ACR               0x00
38 #define FLASH_PECR              0x04
39 #define FLASH_PDKEYR    0x08
40 #define FLASH_PEKEYR    0x0C
41 #define FLASH_PRGKEYR   0x10
42 #define FLASH_OPTKEYR   0x14
43 #define FLASH_SR                0x18
44 #define FLASH_OBR               0x1C
45 #define FLASH_WRPR              0x20
46
47 /* FLASH_ACR bites */
48 #define FLASH_ACR__LATENCY              (1<<0)
49 #define FLASH_ACR__PRFTEN               (1<<1)
50 #define FLASH_ACR__ACC64                (1<<2)
51 #define FLASH_ACR__SLEEP_PD             (1<<3)
52 #define FLASH_ACR__RUN_PD               (1<<4)
53
54 /* FLASH_PECR bits */
55 #define FLASH_PECR__PELOCK              (1<<0)
56 #define FLASH_PECR__PRGLOCK             (1<<1)
57 #define FLASH_PECR__OPTLOCK             (1<<2)
58 #define FLASH_PECR__PROG                (1<<3)
59 #define FLASH_PECR__DATA                (1<<4)
60 #define FLASH_PECR__FTDW                (1<<8)
61 #define FLASH_PECR__ERASE               (1<<9)
62 #define FLASH_PECR__FPRG                (1<<10)
63 #define FLASH_PECR__EOPIE               (1<<16)
64 #define FLASH_PECR__ERRIE               (1<<17)
65 #define FLASH_PECR__OBL_LAUNCH  (1<<18)
66
67 /* FLASH_SR bits */
68 #define FLASH_SR__BSY           (1<<0)
69 #define FLASH_SR__EOP           (1<<1)
70 #define FLASH_SR__ENDHV         (1<<2)
71 #define FLASH_SR__READY         (1<<3)
72 #define FLASH_SR__WRPERR        (1<<8)
73 #define FLASH_SR__PGAERR        (1<<9)
74 #define FLASH_SR__SIZERR        (1<<10)
75 #define FLASH_SR__OPTVERR       (1<<11)
76
77 /* Unlock keys */
78 #define PEKEY1                  0x89ABCDEF
79 #define PEKEY2                  0x02030405
80 #define PRGKEY1                 0x8C9DAEBF
81 #define PRGKEY2                 0x13141516
82 #define OPTKEY1                 0xFBEAD9C8
83 #define OPTKEY2                 0x24252627
84
85 /* other registers */
86 #define DBGMCU_IDCODE           0xE0042000
87 #define DBGMCU_IDCODE_L0        0x40015800
88
89 /* Constants */
90 #define FLASH_SECTOR_SIZE 4096
91 #define FLASH_BANK0_ADDRESS 0x08000000
92
93 /* option bytes */
94 #define OPTION_BYTES_ADDRESS 0x1FF80000
95
96 #define OPTION_BYTE_0_PR1 0xFFFF0000
97 #define OPTION_BYTE_0_PR0 0xFF5500AA
98
99 static int stm32lx_unlock_program_memory(struct flash_bank *bank);
100 static int stm32lx_lock_program_memory(struct flash_bank *bank);
101 static int stm32lx_enable_write_half_page(struct flash_bank *bank);
102 static int stm32lx_erase_sector(struct flash_bank *bank, int sector);
103 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank);
104 static int stm32lx_lock(struct flash_bank *bank);
105 static int stm32lx_unlock(struct flash_bank *bank);
106 static int stm32lx_mass_erase(struct flash_bank *bank);
107 static int stm32lx_wait_until_bsy_clear_timeout(struct flash_bank *bank, int timeout);
108
109 struct stm32lx_rev {
110         uint16_t rev;
111         const char *str;
112 };
113
114 struct stm32lx_part_info {
115         uint16_t id;
116         const char *device_str;
117         const struct stm32lx_rev *revs;
118         size_t num_revs;
119         unsigned int page_size;
120         unsigned int pages_per_sector;
121         uint16_t max_flash_size_kb;
122         uint16_t first_bank_size_kb; /* used when has_dual_banks is true */
123         bool has_dual_banks;
124
125         uint32_t flash_base;    /* Flash controller registers location */
126         uint32_t fsize_base;    /* Location of FSIZE register */
127 };
128
129 struct stm32lx_flash_bank {
130         int probed;
131         uint32_t idcode;
132         uint32_t user_bank_size;
133         uint32_t flash_base;
134
135         const struct stm32lx_part_info *part_info;
136 };
137
138 static const struct stm32lx_rev stm32_416_revs[] = {
139         { 0x1000, "A" }, { 0x1008, "Y" }, { 0x1038, "W" }, { 0x1078, "V" },
140 };
141 static const struct stm32lx_rev stm32_417_revs[] = {
142         { 0x1000, "A" }, { 0x1008, "Z" }, { 0x1018, "Y" }, { 0x1038, "X" }
143 };
144 static const struct stm32lx_rev stm32_425_revs[] = {
145         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2008, "Y" },
146 };
147 static const struct stm32lx_rev stm32_427_revs[] = {
148         { 0x1000, "A" }, { 0x1018, "Y" }, { 0x1038, "X" },
149 };
150 static const struct stm32lx_rev stm32_429_revs[] = {
151         { 0x1000, "A" }, { 0x1018, "Z" },
152 };
153 static const struct stm32lx_rev stm32_436_revs[] = {
154         { 0x1000, "A" }, { 0x1008, "Z" }, { 0x1018, "Y" },
155 };
156 static const struct stm32lx_rev stm32_437_revs[] = {
157         { 0x1000, "A" },
158 };
159 static const struct stm32lx_rev stm32_447_revs[] = {
160         { 0x1000, "A" }, { 0x2000, "B" }, { 0x2008, "Z" },
161 };
162 static const struct stm32lx_rev stm32_457_revs[] = {
163         { 0x1000, "A" }, { 0x1008, "Z" },
164 };
165
166 static const struct stm32lx_part_info stm32lx_parts[] = {
167         {
168                 .id                                     = 0x416,
169                 .revs                           = stm32_416_revs,
170                 .num_revs                       = ARRAY_SIZE(stm32_416_revs),
171                 .device_str                     = "STM32L1xx (Cat.1 - Low/Medium Density)",
172                 .page_size                      = 256,
173                 .pages_per_sector       = 16,
174                 .max_flash_size_kb      = 128,
175                 .has_dual_banks         = false,
176                 .flash_base                     = 0x40023C00,
177                 .fsize_base                     = 0x1FF8004C,
178         },
179         {
180                 .id                                     = 0x417,
181                 .revs                           = stm32_417_revs,
182                 .num_revs                       = ARRAY_SIZE(stm32_417_revs),
183                 .device_str                     = "STM32L0xx (Cat. 3)",
184                 .page_size                      = 128,
185                 .pages_per_sector       = 32,
186                 .max_flash_size_kb      = 64,
187                 .has_dual_banks         = false,
188                 .flash_base                     = 0x40022000,
189                 .fsize_base                     = 0x1FF8007C,
190         },
191         {
192                 .id                                     = 0x425,
193                 .revs                           = stm32_425_revs,
194                 .num_revs                       = ARRAY_SIZE(stm32_425_revs),
195                 .device_str                     = "STM32L0xx (Cat. 2)",
196                 .page_size                      = 128,
197                 .pages_per_sector       = 32,
198                 .max_flash_size_kb      = 32,
199                 .has_dual_banks         = false,
200                 .flash_base                     = 0x40022000,
201                 .fsize_base                     = 0x1FF8007C,
202         },
203         {
204                 .id                                     = 0x427,
205                 .revs                           = stm32_427_revs,
206                 .num_revs                       = ARRAY_SIZE(stm32_427_revs),
207                 .device_str                     = "STM32L1xx (Cat.3 - Medium+ Density)",
208                 .page_size                      = 256,
209                 .pages_per_sector       = 16,
210                 .max_flash_size_kb      = 256,
211                 .has_dual_banks         = false,
212                 .flash_base                     = 0x40023C00,
213                 .fsize_base                     = 0x1FF800CC,
214         },
215         {
216                 .id                                     = 0x429,
217                 .revs                           = stm32_429_revs,
218                 .num_revs                       = ARRAY_SIZE(stm32_429_revs),
219                 .device_str                     = "STM32L1xx (Cat.2)",
220                 .page_size                      = 256,
221                 .pages_per_sector       = 16,
222                 .max_flash_size_kb      = 128,
223                 .has_dual_banks         = false,
224                 .flash_base                     = 0x40023C00,
225                 .fsize_base                     = 0x1FF8004C,
226         },
227         {
228                 .id                                     = 0x436,
229                 .revs                           = stm32_436_revs,
230                 .num_revs                       = ARRAY_SIZE(stm32_436_revs),
231                 .device_str                     = "STM32L1xx (Cat.4/Cat.3 - Medium+/High Density)",
232                 .page_size                      = 256,
233                 .pages_per_sector       = 16,
234                 .max_flash_size_kb      = 384,
235                 .first_bank_size_kb     = 192,
236                 .has_dual_banks         = true,
237                 .flash_base                     = 0x40023C00,
238                 .fsize_base                     = 0x1FF800CC,
239         },
240         {
241                 .id                                     = 0x437,
242                 .revs                           = stm32_437_revs,
243                 .num_revs                       = ARRAY_SIZE(stm32_437_revs),
244                 .device_str                     = "STM32L1xx (Cat.5/Cat.6)",
245                 .page_size                      = 256,
246                 .pages_per_sector       = 16,
247                 .max_flash_size_kb      = 512,
248                 .first_bank_size_kb     = 256,
249                 .has_dual_banks         = true,
250                 .flash_base                     = 0x40023C00,
251                 .fsize_base                     = 0x1FF800CC,
252         },
253         {
254                 .id                                     = 0x447,
255                 .revs                           = stm32_447_revs,
256                 .num_revs                       = ARRAY_SIZE(stm32_447_revs),
257                 .device_str                     = "STM32L0xx (Cat.5)",
258                 .page_size                      = 128,
259                 .pages_per_sector       = 32,
260                 .max_flash_size_kb      = 192,
261                 .first_bank_size_kb     = 128,
262                 .has_dual_banks         = true,
263                 .flash_base                     = 0x40022000,
264                 .fsize_base                     = 0x1FF8007C,
265         },
266         {
267                 .id                                     = 0x457,
268                 .revs                           = stm32_457_revs,
269                 .num_revs                       = ARRAY_SIZE(stm32_457_revs),
270                 .device_str                     = "STM32L0xx (Cat.1)",
271                 .page_size                      = 128,
272                 .pages_per_sector       = 32,
273                 .max_flash_size_kb      = 16,
274                 .has_dual_banks         = false,
275                 .flash_base                     = 0x40022000,
276                 .fsize_base                     = 0x1FF8007C,
277         },
278 };
279
280 /* flash bank stm32lx <base> <size> 0 0 <target#>
281  */
282 FLASH_BANK_COMMAND_HANDLER(stm32lx_flash_bank_command)
283 {
284         struct stm32lx_flash_bank *stm32lx_info;
285         if (CMD_ARGC < 6)
286                 return ERROR_COMMAND_SYNTAX_ERROR;
287
288         /* Create the bank structure */
289         stm32lx_info = calloc(1, sizeof(*stm32lx_info));
290
291         /* Check allocation */
292         if (stm32lx_info == NULL) {
293                 LOG_ERROR("failed to allocate bank structure");
294                 return ERROR_FAIL;
295         }
296
297         bank->driver_priv = stm32lx_info;
298
299         stm32lx_info->probed = 0;
300         stm32lx_info->user_bank_size = bank->size;
301
302         /* the stm32l erased value is 0x00 */
303         bank->default_padded_value = bank->erased_value = 0x00;
304
305         return ERROR_OK;
306 }
307
308 COMMAND_HANDLER(stm32lx_handle_mass_erase_command)
309 {
310         int i;
311
312         if (CMD_ARGC < 1)
313                 return ERROR_COMMAND_SYNTAX_ERROR;
314
315         struct flash_bank *bank;
316         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
317         if (ERROR_OK != retval)
318                 return retval;
319
320         retval = stm32lx_mass_erase(bank);
321         if (retval == ERROR_OK) {
322                 /* set all sectors as erased */
323                 for (i = 0; i < bank->num_sectors; i++)
324                         bank->sectors[i].is_erased = 1;
325
326                 command_print(CMD_CTX, "stm32lx mass erase complete");
327         } else {
328                 command_print(CMD_CTX, "stm32lx mass erase failed");
329         }
330
331         return retval;
332 }
333
334 COMMAND_HANDLER(stm32lx_handle_lock_command)
335 {
336         if (CMD_ARGC < 1)
337                 return ERROR_COMMAND_SYNTAX_ERROR;
338
339         struct flash_bank *bank;
340         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
341         if (ERROR_OK != retval)
342                 return retval;
343
344         retval = stm32lx_lock(bank);
345
346         if (retval == ERROR_OK)
347                 command_print(CMD_CTX, "STM32Lx locked, takes effect after power cycle.");
348         else
349                 command_print(CMD_CTX, "STM32Lx lock failed");
350
351         return retval;
352 }
353
354 COMMAND_HANDLER(stm32lx_handle_unlock_command)
355 {
356         if (CMD_ARGC < 1)
357                 return ERROR_COMMAND_SYNTAX_ERROR;
358
359         struct flash_bank *bank;
360         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
361         if (ERROR_OK != retval)
362                 return retval;
363
364         retval = stm32lx_unlock(bank);
365
366         if (retval == ERROR_OK)
367                 command_print(CMD_CTX, "STM32Lx unlocked, takes effect after power cycle.");
368         else
369                 command_print(CMD_CTX, "STM32Lx unlock failed");
370
371         return retval;
372 }
373
374 static int stm32lx_protect_check(struct flash_bank *bank)
375 {
376         int retval;
377         struct target *target = bank->target;
378         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
379
380         uint32_t wrpr;
381
382         /*
383          * Read the WRPR word, and check each bit (corresponding to each
384          * flash sector
385          */
386         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_WRPR,
387                         &wrpr);
388         if (retval != ERROR_OK)
389                 return retval;
390
391         for (int i = 0; i < bank->num_sectors; i++) {
392                 if (wrpr & (1 << i))
393                         bank->sectors[i].is_protected = 1;
394                 else
395                         bank->sectors[i].is_protected = 0;
396         }
397         return ERROR_OK;
398 }
399
400 static int stm32lx_erase(struct flash_bank *bank, int first, int last)
401 {
402         int retval;
403
404         /*
405          * It could be possible to do a mass erase if all sectors must be
406          * erased, but it is not implemented yet.
407          */
408
409         if (bank->target->state != TARGET_HALTED) {
410                 LOG_ERROR("Target not halted");
411                 return ERROR_TARGET_NOT_HALTED;
412         }
413
414         /*
415          * Loop over the selected sectors and erase them
416          */
417         for (int i = first; i <= last; i++) {
418                 retval = stm32lx_erase_sector(bank, i);
419                 if (retval != ERROR_OK)
420                         return retval;
421                 bank->sectors[i].is_erased = 1;
422         }
423         return ERROR_OK;
424 }
425
426 static int stm32lx_protect(struct flash_bank *bank, int set, int first,
427                 int last)
428 {
429         LOG_WARNING("protection of the STM32L flash is not implemented");
430         return ERROR_OK;
431 }
432
433 static int stm32lx_write_half_pages(struct flash_bank *bank, const uint8_t *buffer,
434                 uint32_t offset, uint32_t count)
435 {
436         struct target *target = bank->target;
437         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
438
439         uint32_t hp_nb = stm32lx_info->part_info->page_size / 2;
440         uint32_t buffer_size = 16384;
441         struct working_area *write_algorithm;
442         struct working_area *source;
443         uint32_t address = bank->base + offset;
444
445         struct reg_param reg_params[3];
446         struct armv7m_algorithm armv7m_info;
447
448         int retval = ERROR_OK;
449
450         /* see contib/loaders/flash/stm32lx.S for src */
451
452         static const uint8_t stm32lx_flash_write_code[] = {
453                         0x92, 0x00, 0x8A, 0x18, 0x01, 0xE0, 0x08, 0xC9, 0x08, 0xC0, 0x91, 0x42, 0xFB, 0xD1, 0x00, 0xBE
454         };
455
456         /* Make sure we're performing a half-page aligned write. */
457         if (count % hp_nb) {
458                 LOG_ERROR("The byte count must be %" PRIu32 "B-aligned but count is %" PRIi32 "B)", hp_nb, count);
459                 return ERROR_FAIL;
460         }
461
462         /* flash write code */
463         if (target_alloc_working_area(target, sizeof(stm32lx_flash_write_code),
464                         &write_algorithm) != ERROR_OK) {
465                 LOG_DEBUG("no working area for block memory writes");
466                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
467         }
468
469         /* Write the flashing code */
470         retval = target_write_buffer(target,
471                         write_algorithm->address,
472                         sizeof(stm32lx_flash_write_code),
473                         stm32lx_flash_write_code);
474         if (retval != ERROR_OK) {
475                 target_free_working_area(target, write_algorithm);
476                 return retval;
477         }
478
479         /* Allocate half pages memory */
480         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
481                 if (buffer_size > 1024)
482                         buffer_size -= 1024;
483                 else
484                         buffer_size /= 2;
485
486                 if (buffer_size <= stm32lx_info->part_info->page_size) {
487                         /* we already allocated the writing code, but failed to get a
488                          * buffer, free the algorithm */
489                         target_free_working_area(target, write_algorithm);
490
491                         LOG_WARNING("no large enough working area available, can't do block memory writes");
492                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
493                 }
494         }
495
496         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
497         armv7m_info.core_mode = ARM_MODE_THREAD;
498         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
499         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
500         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
501
502         /* Enable half-page write */
503         retval = stm32lx_enable_write_half_page(bank);
504         if (retval != ERROR_OK) {
505                 target_free_working_area(target, source);
506                 target_free_working_area(target, write_algorithm);
507
508                 destroy_reg_param(&reg_params[0]);
509                 destroy_reg_param(&reg_params[1]);
510                 destroy_reg_param(&reg_params[2]);
511                 return retval;
512         }
513
514         struct armv7m_common *armv7m = target_to_armv7m(target);
515         if (armv7m == NULL) {
516
517                 /* something is very wrong if armv7m is NULL */
518                 LOG_ERROR("unable to get armv7m target");
519                 return retval;
520         }
521
522         /* save any DEMCR flags and configure target to catch any Hard Faults */
523         uint32_t demcr_save = armv7m->demcr;
524         armv7m->demcr = VC_HARDERR;
525
526         /* Loop while there are bytes to write */
527         while (count > 0) {
528                 uint32_t this_count;
529                 this_count = (count > buffer_size) ? buffer_size : count;
530
531                 /* Write the next half pages */
532                 retval = target_write_buffer(target, source->address, this_count, buffer);
533                 if (retval != ERROR_OK)
534                         break;
535
536                 /* 4: Store useful information in the registers */
537                 /* the destination address of the copy (R0) */
538                 buf_set_u32(reg_params[0].value, 0, 32, address);
539                 /* The source address of the copy (R1) */
540                 buf_set_u32(reg_params[1].value, 0, 32, source->address);
541                 /* The length of the copy (R2) */
542                 buf_set_u32(reg_params[2].value, 0, 32, this_count / 4);
543
544                 /* 5: Execute the bunch of code */
545                 retval = target_run_algorithm(target, 0, NULL, sizeof(reg_params)
546                                 / sizeof(*reg_params), reg_params,
547                                 write_algorithm->address, 0, 10000, &armv7m_info);
548                 if (retval != ERROR_OK)
549                         break;
550
551                 /* check for Hard Fault */
552                 if (armv7m->exception_number == 3)
553                         break;
554
555                 /* 6: Wait while busy */
556                 retval = stm32lx_wait_until_bsy_clear(bank);
557                 if (retval != ERROR_OK)
558                         break;
559
560                 buffer += this_count;
561                 address += this_count;
562                 count -= this_count;
563         }
564
565         /* restore previous flags */
566         armv7m->demcr = demcr_save;
567
568         if (armv7m->exception_number == 3) {
569
570                 /* the stm32l15x devices seem to have an issue when blank.
571                  * if a ram loader is executed on a blank device it will
572                  * Hard Fault, this issue does not happen for a already programmed device.
573                  * A related issue is described in the stm32l151xx errata (Doc ID 17721 Rev 6 - 2.1.3).
574                  * The workaround of handling the Hard Fault exception does work, but makes the
575                  * loader more complicated, as a compromise we manually write the pages, programming time
576                  * is reduced by 50% using this slower method.
577                  */
578
579                 LOG_WARNING("Couldn't use loader, falling back to page memory writes");
580
581                 while (count > 0) {
582                         uint32_t this_count;
583                         this_count = (count > hp_nb) ? hp_nb : count;
584
585                         /* Write the next half pages */
586                         retval = target_write_buffer(target, address, this_count, buffer);
587                         if (retval != ERROR_OK)
588                                 break;
589
590                         /* Wait while busy */
591                         retval = stm32lx_wait_until_bsy_clear(bank);
592                         if (retval != ERROR_OK)
593                                 break;
594
595                         buffer += this_count;
596                         address += this_count;
597                         count -= this_count;
598                 }
599         }
600
601         if (retval == ERROR_OK)
602                 retval = stm32lx_lock_program_memory(bank);
603
604         target_free_working_area(target, source);
605         target_free_working_area(target, write_algorithm);
606
607         destroy_reg_param(&reg_params[0]);
608         destroy_reg_param(&reg_params[1]);
609         destroy_reg_param(&reg_params[2]);
610
611         return retval;
612 }
613
614 static int stm32lx_write(struct flash_bank *bank, const uint8_t *buffer,
615                 uint32_t offset, uint32_t count)
616 {
617         struct target *target = bank->target;
618         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
619
620         uint32_t hp_nb = stm32lx_info->part_info->page_size / 2;
621         uint32_t halfpages_number;
622         uint32_t bytes_remaining = 0;
623         uint32_t address = bank->base + offset;
624         uint32_t bytes_written = 0;
625         int retval, retval2;
626
627         if (bank->target->state != TARGET_HALTED) {
628                 LOG_ERROR("Target not halted");
629                 return ERROR_TARGET_NOT_HALTED;
630         }
631
632         if (offset & 0x3) {
633                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 4-byte alignment", offset);
634                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
635         }
636
637         retval = stm32lx_unlock_program_memory(bank);
638         if (retval != ERROR_OK)
639                 return retval;
640
641         /* first we need to write any unaligned head bytes upto
642          * the next 128 byte page */
643
644         if (offset % hp_nb)
645                 bytes_remaining = MIN(count, hp_nb - (offset % hp_nb));
646
647         while (bytes_remaining > 0) {
648                 uint8_t value[4] = {0xff, 0xff, 0xff, 0xff};
649
650                 /* copy remaining bytes into the write buffer */
651                 uint32_t bytes_to_write = MIN(4, bytes_remaining);
652                 memcpy(value, buffer + bytes_written, bytes_to_write);
653
654                 retval = target_write_buffer(target, address, 4, value);
655                 if (retval != ERROR_OK)
656                         goto reset_pg_and_lock;
657
658                 bytes_written += bytes_to_write;
659                 bytes_remaining -= bytes_to_write;
660                 address += 4;
661
662                 retval = stm32lx_wait_until_bsy_clear(bank);
663                 if (retval != ERROR_OK)
664                         goto reset_pg_and_lock;
665         }
666
667         offset += bytes_written;
668         count -= bytes_written;
669
670         /* this should always pass this check here */
671         assert((offset % hp_nb) == 0);
672
673         /* calculate half pages */
674         halfpages_number = count / hp_nb;
675
676         if (halfpages_number) {
677                 retval = stm32lx_write_half_pages(bank, buffer + bytes_written, offset, hp_nb * halfpages_number);
678                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
679                         /* attempt slow memory writes */
680                         LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
681                         halfpages_number = 0;
682                 } else {
683                         if (retval != ERROR_OK)
684                                 return ERROR_FAIL;
685                 }
686         }
687
688         /* write any remaining bytes */
689         uint32_t page_bytes_written = hp_nb * halfpages_number;
690         bytes_written += page_bytes_written;
691         address += page_bytes_written;
692         bytes_remaining = count - page_bytes_written;
693
694         retval = stm32lx_unlock_program_memory(bank);
695         if (retval != ERROR_OK)
696                 return retval;
697
698         while (bytes_remaining > 0) {
699                 uint8_t value[4] = {0xff, 0xff, 0xff, 0xff};
700
701                 /* copy remaining bytes into the write buffer */
702                 uint32_t bytes_to_write = MIN(4, bytes_remaining);
703                 memcpy(value, buffer + bytes_written, bytes_to_write);
704
705                 retval = target_write_buffer(target, address, 4, value);
706                 if (retval != ERROR_OK)
707                         goto reset_pg_and_lock;
708
709                 bytes_written += bytes_to_write;
710                 bytes_remaining -= bytes_to_write;
711                 address += 4;
712
713                 retval = stm32lx_wait_until_bsy_clear(bank);
714                 if (retval != ERROR_OK)
715                         goto reset_pg_and_lock;
716         }
717
718 reset_pg_and_lock:
719         retval2 = stm32lx_lock_program_memory(bank);
720         if (retval == ERROR_OK)
721                 retval = retval2;
722
723         return retval;
724 }
725
726 static int stm32lx_read_id_code(struct target *target, uint32_t *id)
727 {
728         /* read stm32 device id register */
729         int retval = target_read_u32(target, DBGMCU_IDCODE, id);
730         if (retval != ERROR_OK)
731                 return retval;
732
733         /* STM32L0 parts will have 0 there, try reading the L0's location for
734          * DBG_IDCODE in case this is an L0 part. */
735         if (*id == 0)
736                 retval = target_read_u32(target, DBGMCU_IDCODE_L0, id);
737
738         return retval;
739 }
740
741 static int stm32lx_probe(struct flash_bank *bank)
742 {
743         struct target *target = bank->target;
744         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
745         int i;
746         uint16_t flash_size_in_kb;
747         uint32_t device_id;
748         uint32_t base_address = FLASH_BANK0_ADDRESS;
749         uint32_t second_bank_base;
750
751         stm32lx_info->probed = 0;
752         stm32lx_info->part_info = NULL;
753
754         int retval = stm32lx_read_id_code(bank->target, &device_id);
755         if (retval != ERROR_OK)
756                 return retval;
757
758         stm32lx_info->idcode = device_id;
759
760         LOG_DEBUG("device id = 0x%08" PRIx32 "", device_id);
761
762         for (unsigned int n = 0; n < ARRAY_SIZE(stm32lx_parts); n++) {
763                 if ((device_id & 0xfff) == stm32lx_parts[n].id)
764                         stm32lx_info->part_info = &stm32lx_parts[n];
765         }
766
767         if (!stm32lx_info->part_info) {
768                 LOG_WARNING("Cannot identify target as a STM32L family.");
769                 return ERROR_FAIL;
770         } else {
771                 LOG_INFO("Device: %s", stm32lx_info->part_info->device_str);
772         }
773
774         stm32lx_info->flash_base = stm32lx_info->part_info->flash_base;
775
776         /* Get the flash size from target. */
777         retval = target_read_u16(target, stm32lx_info->part_info->fsize_base,
778                         &flash_size_in_kb);
779
780         /* 0x436 devices report their flash size as a 0 or 1 code indicating 384K
781          * or 256K, respectively.  Please see RM0038 r8 or newer and refer to
782          * section 30.1.1. */
783         if (retval == ERROR_OK && (device_id & 0xfff) == 0x436) {
784                 if (flash_size_in_kb == 0)
785                         flash_size_in_kb = 384;
786                 else if (flash_size_in_kb == 1)
787                         flash_size_in_kb = 256;
788         }
789
790         /* Failed reading flash size or flash size invalid (early silicon),
791          * default to max target family */
792         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
793                 LOG_WARNING("STM32L flash size failed, probe inaccurate - assuming %dk flash",
794                         stm32lx_info->part_info->max_flash_size_kb);
795                 flash_size_in_kb = stm32lx_info->part_info->max_flash_size_kb;
796         } else if (flash_size_in_kb > stm32lx_info->part_info->max_flash_size_kb) {
797                 LOG_WARNING("STM32L probed flash size assumed incorrect since FLASH_SIZE=%dk > %dk, - assuming %dk flash",
798                         flash_size_in_kb, stm32lx_info->part_info->max_flash_size_kb,
799                         stm32lx_info->part_info->max_flash_size_kb);
800                 flash_size_in_kb = stm32lx_info->part_info->max_flash_size_kb;
801         }
802
803         if (stm32lx_info->part_info->has_dual_banks) {
804                 /* Use the configured base address to determine if this is the first or second flash bank.
805                  * Verify that the base address is reasonably correct and determine the flash bank size
806                  */
807                 second_bank_base = base_address +
808                         stm32lx_info->part_info->first_bank_size_kb * 1024;
809                 if (bank->base == second_bank_base || !bank->base) {
810                         /* This is the second bank  */
811                         base_address = second_bank_base;
812                         flash_size_in_kb = flash_size_in_kb -
813                                 stm32lx_info->part_info->first_bank_size_kb;
814                 } else if (bank->base == base_address) {
815                         /* This is the first bank */
816                         flash_size_in_kb = stm32lx_info->part_info->first_bank_size_kb;
817                 } else {
818                         LOG_WARNING("STM32L flash bank base address config is incorrect."
819                                     " 0x%" PRIx32 " but should rather be 0x%" PRIx32 " or 0x%" PRIx32,
820                                                 bank->base, base_address, second_bank_base);
821                         return ERROR_FAIL;
822                 }
823                 LOG_INFO("STM32L flash has dual banks. Bank (%d) size is %dkb, base address is 0x%" PRIx32,
824                                 bank->bank_number, flash_size_in_kb, base_address);
825         } else {
826                 LOG_INFO("STM32L flash size is %dkb, base address is 0x%" PRIx32, flash_size_in_kb, base_address);
827         }
828
829         /* if the user sets the size manually then ignore the probed value
830          * this allows us to work around devices that have a invalid flash size register value */
831         if (stm32lx_info->user_bank_size) {
832                 flash_size_in_kb = stm32lx_info->user_bank_size / 1024;
833                 LOG_INFO("ignoring flash probed value, using configured bank size: %dkbytes", flash_size_in_kb);
834         }
835
836         /* calculate numbers of sectors (4kB per sector) */
837         int num_sectors = (flash_size_in_kb * 1024) / FLASH_SECTOR_SIZE;
838
839         if (bank->sectors) {
840                 free(bank->sectors);
841                 bank->sectors = NULL;
842         }
843
844         bank->size = flash_size_in_kb * 1024;
845         bank->base = base_address;
846         bank->num_sectors = num_sectors;
847         bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
848         if (bank->sectors == NULL) {
849                 LOG_ERROR("failed to allocate bank sectors");
850                 return ERROR_FAIL;
851         }
852
853         for (i = 0; i < num_sectors; i++) {
854                 bank->sectors[i].offset = i * FLASH_SECTOR_SIZE;
855                 bank->sectors[i].size = FLASH_SECTOR_SIZE;
856                 bank->sectors[i].is_erased = -1;
857                 bank->sectors[i].is_protected = 1;
858         }
859
860         stm32lx_info->probed = 1;
861
862         return ERROR_OK;
863 }
864
865 static int stm32lx_auto_probe(struct flash_bank *bank)
866 {
867         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
868
869         if (stm32lx_info->probed)
870                 return ERROR_OK;
871
872         return stm32lx_probe(bank);
873 }
874
875 /* This method must return a string displaying information about the bank */
876 static int stm32lx_get_info(struct flash_bank *bank, char *buf, int buf_size)
877 {
878         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
879
880         if (!stm32lx_info->probed) {
881                 int retval = stm32lx_probe(bank);
882                 if (retval != ERROR_OK) {
883                         snprintf(buf, buf_size,
884                                 "Unable to find bank information.");
885                         return retval;
886                 }
887         }
888
889         const struct stm32lx_part_info *info = stm32lx_info->part_info;
890
891         if (info) {
892                 const char *rev_str = NULL;
893                 uint16_t rev_id = stm32lx_info->idcode >> 16;
894
895                 for (unsigned int i = 0; i < info->num_revs; i++)
896                         if (rev_id == info->revs[i].rev)
897                                 rev_str = info->revs[i].str;
898
899                 if (rev_str != NULL) {
900                         snprintf(buf, buf_size,
901                                 "%s - Rev: %s",
902                                 stm32lx_info->part_info->device_str, rev_str);
903                 } else {
904                         snprintf(buf, buf_size,
905                                 "%s - Rev: unknown (0x%04x)",
906                                 stm32lx_info->part_info->device_str, rev_id);
907                 }
908
909                 return ERROR_OK;
910         } else {
911                 snprintf(buf, buf_size, "Cannot identify target as a STM32Lx");
912
913                 return ERROR_FAIL;
914         }
915 }
916
917 static const struct command_registration stm32lx_exec_command_handlers[] = {
918         {
919                 .name = "mass_erase",
920                 .handler = stm32lx_handle_mass_erase_command,
921                 .mode = COMMAND_EXEC,
922                 .usage = "bank_id",
923                 .help = "Erase entire flash device. including available EEPROM",
924         },
925         {
926                 .name = "lock",
927                 .handler = stm32lx_handle_lock_command,
928                 .mode = COMMAND_EXEC,
929                 .usage = "bank_id",
930                 .help = "Increase the readout protection to Level 1.",
931         },
932         {
933                 .name = "unlock",
934                 .handler = stm32lx_handle_unlock_command,
935                 .mode = COMMAND_EXEC,
936                 .usage = "bank_id",
937                 .help = "Lower the readout protection from Level 1 to 0.",
938         },
939         COMMAND_REGISTRATION_DONE
940 };
941
942 static const struct command_registration stm32lx_command_handlers[] = {
943         {
944                 .name = "stm32lx",
945                 .mode = COMMAND_ANY,
946                 .help = "stm32lx flash command group",
947                 .usage = "",
948                 .chain = stm32lx_exec_command_handlers,
949         },
950         COMMAND_REGISTRATION_DONE
951 };
952
953 struct flash_driver stm32lx_flash = {
954                 .name = "stm32lx",
955                 .commands = stm32lx_command_handlers,
956                 .flash_bank_command = stm32lx_flash_bank_command,
957                 .erase = stm32lx_erase,
958                 .protect = stm32lx_protect,
959                 .write = stm32lx_write,
960                 .read = default_flash_read,
961                 .probe = stm32lx_probe,
962                 .auto_probe = stm32lx_auto_probe,
963                 .erase_check = default_flash_blank_check,
964                 .protect_check = stm32lx_protect_check,
965                 .info = stm32lx_get_info,
966 };
967
968 /* Static methods implementation */
969 static int stm32lx_unlock_program_memory(struct flash_bank *bank)
970 {
971         struct target *target = bank->target;
972         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
973         int retval;
974         uint32_t reg32;
975
976         /*
977          * Unlocking the program memory is done by unlocking the PECR,
978          * then by writing the 2 PRGKEY to the PRGKEYR register
979          */
980
981         /* check flash is not already unlocked */
982         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
983                         &reg32);
984         if (retval != ERROR_OK)
985                 return retval;
986
987         if ((reg32 & FLASH_PECR__PRGLOCK) == 0)
988                 return ERROR_OK;
989
990         /* To unlock the PECR write the 2 PEKEY to the PEKEYR register */
991         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR,
992                         PEKEY1);
993         if (retval != ERROR_OK)
994                 return retval;
995
996         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR,
997                         PEKEY2);
998         if (retval != ERROR_OK)
999                 return retval;
1000
1001         /* Make sure it worked */
1002         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1003                         &reg32);
1004         if (retval != ERROR_OK)
1005                 return retval;
1006
1007         if (reg32 & FLASH_PECR__PELOCK) {
1008                 LOG_ERROR("PELOCK is not cleared :(");
1009                 return ERROR_FLASH_OPERATION_FAILED;
1010         }
1011
1012         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PRGKEYR,
1013                         PRGKEY1);
1014         if (retval != ERROR_OK)
1015                 return retval;
1016         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PRGKEYR,
1017                         PRGKEY2);
1018         if (retval != ERROR_OK)
1019                 return retval;
1020
1021         /* Make sure it worked */
1022         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1023                         &reg32);
1024         if (retval != ERROR_OK)
1025                 return retval;
1026
1027         if (reg32 & FLASH_PECR__PRGLOCK) {
1028                 LOG_ERROR("PRGLOCK is not cleared :(");
1029                 return ERROR_FLASH_OPERATION_FAILED;
1030         }
1031
1032         return ERROR_OK;
1033 }
1034
1035 static int stm32lx_enable_write_half_page(struct flash_bank *bank)
1036 {
1037         struct target *target = bank->target;
1038         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1039         int retval;
1040         uint32_t reg32;
1041
1042         /**
1043          * Unlock the program memory, then set the FPRG bit in the PECR register.
1044          */
1045         retval = stm32lx_unlock_program_memory(bank);
1046         if (retval != ERROR_OK)
1047                 return retval;
1048
1049         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1050                         &reg32);
1051         if (retval != ERROR_OK)
1052                 return retval;
1053
1054         reg32 |= FLASH_PECR__FPRG;
1055         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1056                         reg32);
1057         if (retval != ERROR_OK)
1058                 return retval;
1059
1060         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1061                         &reg32);
1062         if (retval != ERROR_OK)
1063                 return retval;
1064
1065         reg32 |= FLASH_PECR__PROG;
1066         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1067                         reg32);
1068
1069         return retval;
1070 }
1071
1072 static int stm32lx_lock_program_memory(struct flash_bank *bank)
1073 {
1074         struct target *target = bank->target;
1075         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1076         int retval;
1077         uint32_t reg32;
1078
1079         /* To lock the program memory, simply set the lock bit and lock PECR */
1080
1081         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1082                         &reg32);
1083         if (retval != ERROR_OK)
1084                 return retval;
1085
1086         reg32 |= FLASH_PECR__PRGLOCK;
1087         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1088                         reg32);
1089         if (retval != ERROR_OK)
1090                 return retval;
1091
1092         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1093                         &reg32);
1094         if (retval != ERROR_OK)
1095                 return retval;
1096
1097         reg32 |= FLASH_PECR__PELOCK;
1098         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1099                         reg32);
1100         if (retval != ERROR_OK)
1101                 return retval;
1102
1103         return ERROR_OK;
1104 }
1105
1106 static int stm32lx_erase_sector(struct flash_bank *bank, int sector)
1107 {
1108         struct target *target = bank->target;
1109         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1110         int retval;
1111         uint32_t reg32;
1112
1113         /*
1114          * To erase a sector (i.e. stm32lx_info->part_info.pages_per_sector pages),
1115          * first unlock the memory, loop over the pages of this sector
1116          * and write 0x0 to its first word.
1117          */
1118
1119         retval = stm32lx_unlock_program_memory(bank);
1120         if (retval != ERROR_OK)
1121                 return retval;
1122
1123         for (int page = 0; page < (int)stm32lx_info->part_info->pages_per_sector;
1124                         page++) {
1125                 reg32 = FLASH_PECR__PROG | FLASH_PECR__ERASE;
1126                 retval = target_write_u32(target,
1127                                 stm32lx_info->flash_base + FLASH_PECR, reg32);
1128                 if (retval != ERROR_OK)
1129                         return retval;
1130
1131                 retval = stm32lx_wait_until_bsy_clear(bank);
1132                 if (retval != ERROR_OK)
1133                         return retval;
1134
1135                 uint32_t addr = bank->base + bank->sectors[sector].offset + (page
1136                                 * stm32lx_info->part_info->page_size);
1137                 retval = target_write_u32(target, addr, 0x0);
1138                 if (retval != ERROR_OK)
1139                         return retval;
1140
1141                 retval = stm32lx_wait_until_bsy_clear(bank);
1142                 if (retval != ERROR_OK)
1143                         return retval;
1144         }
1145
1146         retval = stm32lx_lock_program_memory(bank);
1147         if (retval != ERROR_OK)
1148                 return retval;
1149
1150         return ERROR_OK;
1151 }
1152
1153 static inline int stm32lx_get_flash_status(struct flash_bank *bank, uint32_t *status)
1154 {
1155         struct target *target = bank->target;
1156         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1157
1158         return target_read_u32(target, stm32lx_info->flash_base + FLASH_SR, status);
1159 }
1160
1161 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank)
1162 {
1163         return stm32lx_wait_until_bsy_clear_timeout(bank, 100);
1164 }
1165
1166 static int stm32lx_unlock_options_bytes(struct flash_bank *bank)
1167 {
1168         struct target *target = bank->target;
1169         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1170         int retval;
1171         uint32_t reg32;
1172
1173         /*
1174         * Unlocking the options bytes is done by unlocking the PECR,
1175         * then by writing the 2 FLASH_PEKEYR to the FLASH_OPTKEYR register
1176         */
1177
1178         /* check flash is not already unlocked */
1179         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR, &reg32);
1180         if (retval != ERROR_OK)
1181                 return retval;
1182
1183         if ((reg32 & FLASH_PECR__OPTLOCK) == 0)
1184                 return ERROR_OK;
1185
1186         if ((reg32 & FLASH_PECR__PELOCK) != 0) {
1187
1188                 retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR, PEKEY1);
1189                 if (retval != ERROR_OK)
1190                         return retval;
1191
1192                 retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR, PEKEY2);
1193                 if (retval != ERROR_OK)
1194                         return retval;
1195         }
1196
1197         /* To unlock the PECR write the 2 OPTKEY to the FLASH_OPTKEYR register */
1198         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_OPTKEYR, OPTKEY1);
1199         if (retval != ERROR_OK)
1200                 return retval;
1201
1202         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_OPTKEYR, OPTKEY2);
1203         if (retval != ERROR_OK)
1204                 return retval;
1205
1206         return ERROR_OK;
1207 }
1208
1209 static int stm32lx_wait_until_bsy_clear_timeout(struct flash_bank *bank, int timeout)
1210 {
1211         struct target *target = bank->target;
1212         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1213         uint32_t status;
1214         int retval = ERROR_OK;
1215
1216         /* wait for busy to clear */
1217         for (;;) {
1218                 retval = stm32lx_get_flash_status(bank, &status);
1219                 if (retval != ERROR_OK)
1220                         return retval;
1221
1222                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
1223                 if ((status & FLASH_SR__BSY) == 0)
1224                         break;
1225
1226                 if (timeout-- <= 0) {
1227                         LOG_ERROR("timed out waiting for flash");
1228                         return ERROR_FAIL;
1229                 }
1230                 alive_sleep(1);
1231         }
1232
1233         if (status & FLASH_SR__WRPERR) {
1234                 LOG_ERROR("access denied / write protected");
1235                 retval = ERROR_FAIL;
1236         }
1237
1238         if (status & FLASH_SR__PGAERR) {
1239                 LOG_ERROR("invalid program address");
1240                 retval = ERROR_FAIL;
1241         }
1242
1243         /* Clear but report errors */
1244         if (status & FLASH_SR__OPTVERR) {
1245                 /* If this operation fails, we ignore it and report the original retval */
1246                 target_write_u32(target, stm32lx_info->flash_base + FLASH_SR, status & FLASH_SR__OPTVERR);
1247         }
1248
1249         return retval;
1250 }
1251
1252 static int stm32lx_obl_launch(struct flash_bank *bank)
1253 {
1254         struct target *target = bank->target;
1255         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1256         int retval;
1257
1258         /* This will fail as the target gets immediately rebooted */
1259         target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1260                          FLASH_PECR__OBL_LAUNCH);
1261
1262         size_t tries = 10;
1263         do {
1264                 target_halt(target);
1265                 retval = target_poll(target);
1266         } while (--tries > 0 &&
1267                  (retval != ERROR_OK || target->state != TARGET_HALTED));
1268
1269         return tries ? ERROR_OK : ERROR_FAIL;
1270 }
1271
1272 static int stm32lx_lock(struct flash_bank *bank)
1273 {
1274         int retval;
1275         struct target *target = bank->target;
1276
1277         if (target->state != TARGET_HALTED) {
1278                 LOG_ERROR("Target not halted");
1279                 return ERROR_TARGET_NOT_HALTED;
1280         }
1281
1282         retval = stm32lx_unlock_options_bytes(bank);
1283         if (retval != ERROR_OK)
1284                 return retval;
1285
1286         /* set the RDP protection level to 1 */
1287         retval = target_write_u32(target, OPTION_BYTES_ADDRESS, OPTION_BYTE_0_PR1);
1288         if (retval != ERROR_OK)
1289                 return retval;
1290
1291         return ERROR_OK;
1292 }
1293
1294 static int stm32lx_unlock(struct flash_bank *bank)
1295 {
1296         int retval;
1297         struct target *target = bank->target;
1298
1299         if (target->state != TARGET_HALTED) {
1300                 LOG_ERROR("Target not halted");
1301                 return ERROR_TARGET_NOT_HALTED;
1302         }
1303
1304         retval = stm32lx_unlock_options_bytes(bank);
1305         if (retval != ERROR_OK)
1306                 return retval;
1307
1308         /* set the RDP protection level to 0 */
1309         retval = target_write_u32(target, OPTION_BYTES_ADDRESS, OPTION_BYTE_0_PR0);
1310         if (retval != ERROR_OK)
1311                 return retval;
1312
1313         retval = stm32lx_wait_until_bsy_clear_timeout(bank, 30000);
1314         if (retval != ERROR_OK)
1315                 return retval;
1316
1317         return ERROR_OK;
1318 }
1319
1320 static int stm32lx_mass_erase(struct flash_bank *bank)
1321 {
1322         int retval;
1323         struct target *target = bank->target;
1324         struct stm32lx_flash_bank *stm32lx_info = NULL;
1325         uint32_t reg32;
1326
1327         if (target->state != TARGET_HALTED) {
1328                 LOG_ERROR("Target not halted");
1329                 return ERROR_TARGET_NOT_HALTED;
1330         }
1331
1332         stm32lx_info = bank->driver_priv;
1333
1334         retval = stm32lx_lock(bank);
1335         if (retval != ERROR_OK)
1336                 return retval;
1337
1338         retval = stm32lx_obl_launch(bank);
1339         if (retval != ERROR_OK)
1340                 return retval;
1341
1342         retval = stm32lx_unlock(bank);
1343         if (retval != ERROR_OK)
1344                 return retval;
1345
1346         retval = stm32lx_obl_launch(bank);
1347         if (retval != ERROR_OK)
1348                 return retval;
1349
1350         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR, &reg32);
1351         if (retval != ERROR_OK)
1352                 return retval;
1353
1354         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR, reg32 | FLASH_PECR__OPTLOCK);
1355         if (retval != ERROR_OK)
1356                 return retval;
1357
1358         return ERROR_OK;
1359 }