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