stm32lx.c: Print device string as info.
[fw/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         } else {
744                 LOG_INFO("Device: %s", stm32lx_info->part_info->device_str);
745         }
746
747         stm32lx_info->flash_base = stm32lx_info->part_info->flash_base;
748
749         /* Get the flash size from target. */
750         retval = target_read_u16(target, stm32lx_info->part_info->fsize_base,
751                         &flash_size_in_kb);
752
753         /* 0x436 devices report their flash size as a 0 or 1 code indicating 384K
754          * or 256K, respectively.  Please see RM0038 r8 or newer and refer to
755          * section 30.1.1. */
756         if (retval == ERROR_OK && (device_id & 0xfff) == 0x436) {
757                 if (flash_size_in_kb == 0)
758                         flash_size_in_kb = 384;
759                 else if (flash_size_in_kb == 1)
760                         flash_size_in_kb = 256;
761         }
762
763         /* Failed reading flash size or flash size invalid (early silicon),
764          * default to max target family */
765         if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
766                 LOG_WARNING("STM32L flash size failed, probe inaccurate - assuming %dk flash",
767                         stm32lx_info->part_info->max_flash_size_kb);
768                 flash_size_in_kb = stm32lx_info->part_info->max_flash_size_kb;
769         } else if (flash_size_in_kb > stm32lx_info->part_info->max_flash_size_kb) {
770                 LOG_WARNING("STM32L probed flash size assumed incorrect since FLASH_SIZE=%dk > %dk, - assuming %dk flash",
771                         flash_size_in_kb, stm32lx_info->part_info->max_flash_size_kb,
772                         stm32lx_info->part_info->max_flash_size_kb);
773                 flash_size_in_kb = stm32lx_info->part_info->max_flash_size_kb;
774         }
775
776         if (stm32lx_info->part_info->has_dual_banks) {
777                 /* Use the configured base address to determine if this is the first or second flash bank.
778                  * Verify that the base address is reasonably correct and determine the flash bank size
779                  */
780                 second_bank_base = base_address +
781                         stm32lx_info->part_info->first_bank_size_kb * 1024;
782                 if (bank->base == second_bank_base || !bank->base) {
783                         /* This is the second bank  */
784                         base_address = second_bank_base;
785                         flash_size_in_kb = flash_size_in_kb -
786                                 stm32lx_info->part_info->first_bank_size_kb;
787                 } else if (bank->base == base_address) {
788                         /* This is the first bank */
789                         flash_size_in_kb = stm32lx_info->part_info->first_bank_size_kb;
790                 } else {
791                         LOG_WARNING("STM32L flash bank base address config is incorrect."
792                                     " 0x%" PRIx32 " but should rather be 0x%" PRIx32 " or 0x%" PRIx32,
793                                                 bank->base, base_address, second_bank_base);
794                         return ERROR_FAIL;
795                 }
796                 LOG_INFO("STM32L flash has dual banks. Bank (%d) size is %dkb, base address is 0x%" PRIx32,
797                                 bank->bank_number, flash_size_in_kb, base_address);
798         } else {
799                 LOG_INFO("STM32L flash size is %dkb, base address is 0x%" PRIx32, flash_size_in_kb, base_address);
800         }
801
802         /* if the user sets the size manually then ignore the probed value
803          * this allows us to work around devices that have a invalid flash size register value */
804         if (stm32lx_info->user_bank_size) {
805                 flash_size_in_kb = stm32lx_info->user_bank_size / 1024;
806                 LOG_INFO("ignoring flash probed value, using configured bank size: %dkbytes", flash_size_in_kb);
807         }
808
809         /* calculate numbers of sectors (4kB per sector) */
810         int num_sectors = (flash_size_in_kb * 1024) / FLASH_SECTOR_SIZE;
811
812         if (bank->sectors) {
813                 free(bank->sectors);
814                 bank->sectors = NULL;
815         }
816
817         bank->size = flash_size_in_kb * 1024;
818         bank->base = base_address;
819         bank->num_sectors = num_sectors;
820         bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
821         if (bank->sectors == NULL) {
822                 LOG_ERROR("failed to allocate bank sectors");
823                 return ERROR_FAIL;
824         }
825
826         for (i = 0; i < num_sectors; i++) {
827                 bank->sectors[i].offset = i * FLASH_SECTOR_SIZE;
828                 bank->sectors[i].size = FLASH_SECTOR_SIZE;
829                 bank->sectors[i].is_erased = -1;
830                 bank->sectors[i].is_protected = 1;
831         }
832
833         stm32lx_info->probed = 1;
834
835         return ERROR_OK;
836 }
837
838 static int stm32lx_auto_probe(struct flash_bank *bank)
839 {
840         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
841
842         if (stm32lx_info->probed)
843                 return ERROR_OK;
844
845         return stm32lx_probe(bank);
846 }
847
848 static int stm32lx_erase_check(struct flash_bank *bank)
849 {
850         struct target *target = bank->target;
851         const int buffer_size = 4096;
852         int i;
853         uint32_t nBytes;
854         int retval = ERROR_OK;
855
856         if (bank->target->state != TARGET_HALTED) {
857                 LOG_ERROR("Target not halted");
858                 return ERROR_TARGET_NOT_HALTED;
859         }
860
861         uint8_t *buffer = malloc(buffer_size);
862         if (buffer == NULL) {
863                 LOG_ERROR("failed to allocate read buffer");
864                 return ERROR_FAIL;
865         }
866
867         for (i = 0; i < bank->num_sectors; i++) {
868                 uint32_t j;
869                 bank->sectors[i].is_erased = 1;
870
871                 /* Loop chunk by chunk over the sector */
872                 for (j = 0; j < bank->sectors[i].size; j += buffer_size) {
873                         uint32_t chunk;
874                         chunk = buffer_size;
875                         if (chunk > (j - bank->sectors[i].size))
876                                 chunk = (j - bank->sectors[i].size);
877
878                         retval = target_read_memory(target, bank->base
879                                         + bank->sectors[i].offset + j, 4, chunk / 4, buffer);
880                         if (retval != ERROR_OK)
881                                 break;
882
883                         for (nBytes = 0; nBytes < chunk; nBytes++) {
884                                 if (buffer[nBytes] != 0x00) {
885                                         bank->sectors[i].is_erased = 0;
886                                         break;
887                                 }
888                         }
889                 }
890                 if (retval != ERROR_OK)
891                         break;
892         }
893         free(buffer);
894
895         return retval;
896 }
897
898 /* This method must return a string displaying information about the bank */
899 static int stm32lx_get_info(struct flash_bank *bank, char *buf, int buf_size)
900 {
901         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
902
903         if (!stm32lx_info->probed) {
904                 int retval = stm32lx_probe(bank);
905                 if (retval != ERROR_OK) {
906                         snprintf(buf, buf_size,
907                                 "Unable to find bank information.");
908                         return retval;
909                 }
910         }
911
912         const struct stm32lx_part_info *info = stm32lx_info->part_info;
913
914         if (info) {
915                 const char *rev_str = NULL;
916                 uint16_t rev_id = stm32lx_info->idcode >> 16;
917
918                 for (unsigned int i = 0; i < info->num_revs; i++)
919                         if (rev_id == info->revs[i].rev)
920                                 rev_str = info->revs[i].str;
921
922                 if (rev_str != NULL) {
923                         snprintf(buf, buf_size,
924                                 "%s - Rev: %s",
925                                 stm32lx_info->part_info->device_str, rev_str);
926                 } else {
927                         snprintf(buf, buf_size,
928                                 "%s - Rev: unknown (0x%04x)",
929                                 stm32lx_info->part_info->device_str, rev_id);
930                 }
931
932                 return ERROR_OK;
933         } else {
934                 snprintf(buf, buf_size, "Cannot identify target as a STM32Lx");
935
936                 return ERROR_FAIL;
937         }
938 }
939
940 static const struct command_registration stm32lx_exec_command_handlers[] = {
941         {
942                 .name = "mass_erase",
943                 .handler = stm32lx_handle_mass_erase_command,
944                 .mode = COMMAND_EXEC,
945                 .usage = "bank_id",
946                 .help = "Erase entire flash device. including available EEPROM",
947         },
948         COMMAND_REGISTRATION_DONE
949 };
950
951 static const struct command_registration stm32lx_command_handlers[] = {
952         {
953                 .name = "stm32lx",
954                 .mode = COMMAND_ANY,
955                 .help = "stm32lx flash command group",
956                 .usage = "",
957                 .chain = stm32lx_exec_command_handlers,
958         },
959         COMMAND_REGISTRATION_DONE
960 };
961
962 struct flash_driver stm32lx_flash = {
963                 .name = "stm32lx",
964                 .commands = stm32lx_command_handlers,
965                 .flash_bank_command = stm32lx_flash_bank_command,
966                 .erase = stm32lx_erase,
967                 .protect = stm32lx_protect,
968                 .write = stm32lx_write,
969                 .read = default_flash_read,
970                 .probe = stm32lx_probe,
971                 .auto_probe = stm32lx_auto_probe,
972                 .erase_check = stm32lx_erase_check,
973                 .protect_check = stm32lx_protect_check,
974                 .info = stm32lx_get_info,
975 };
976
977 /* Static methods implementation */
978 static int stm32lx_unlock_program_memory(struct flash_bank *bank)
979 {
980         struct target *target = bank->target;
981         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
982         int retval;
983         uint32_t reg32;
984
985         /*
986          * Unlocking the program memory is done by unlocking the PECR,
987          * then by writing the 2 PRGKEY to the PRGKEYR register
988          */
989
990         /* check flash is not already unlocked */
991         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
992                         &reg32);
993         if (retval != ERROR_OK)
994                 return retval;
995
996         if ((reg32 & FLASH_PECR__PRGLOCK) == 0)
997                 return ERROR_OK;
998
999         /* To unlock the PECR write the 2 PEKEY to the PEKEYR register */
1000         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR,
1001                         PEKEY1);
1002         if (retval != ERROR_OK)
1003                 return retval;
1004
1005         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR,
1006                         PEKEY2);
1007         if (retval != ERROR_OK)
1008                 return retval;
1009
1010         /* Make sure it worked */
1011         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1012                         &reg32);
1013         if (retval != ERROR_OK)
1014                 return retval;
1015
1016         if (reg32 & FLASH_PECR__PELOCK) {
1017                 LOG_ERROR("PELOCK is not cleared :(");
1018                 return ERROR_FLASH_OPERATION_FAILED;
1019         }
1020
1021         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PRGKEYR,
1022                         PRGKEY1);
1023         if (retval != ERROR_OK)
1024                 return retval;
1025         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PRGKEYR,
1026                         PRGKEY2);
1027         if (retval != ERROR_OK)
1028                 return retval;
1029
1030         /* Make sure it worked */
1031         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1032                         &reg32);
1033         if (retval != ERROR_OK)
1034                 return retval;
1035
1036         if (reg32 & FLASH_PECR__PRGLOCK) {
1037                 LOG_ERROR("PRGLOCK is not cleared :(");
1038                 return ERROR_FLASH_OPERATION_FAILED;
1039         }
1040
1041         return ERROR_OK;
1042 }
1043
1044 static int stm32lx_enable_write_half_page(struct flash_bank *bank)
1045 {
1046         struct target *target = bank->target;
1047         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1048         int retval;
1049         uint32_t reg32;
1050
1051         /**
1052          * Unlock the program memory, then set the FPRG bit in the PECR register.
1053          */
1054         retval = stm32lx_unlock_program_memory(bank);
1055         if (retval != ERROR_OK)
1056                 return retval;
1057
1058         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1059                         &reg32);
1060         if (retval != ERROR_OK)
1061                 return retval;
1062
1063         reg32 |= FLASH_PECR__FPRG;
1064         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1065                         reg32);
1066         if (retval != ERROR_OK)
1067                 return retval;
1068
1069         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1070                         &reg32);
1071         if (retval != ERROR_OK)
1072                 return retval;
1073
1074         reg32 |= FLASH_PECR__PROG;
1075         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1076                         reg32);
1077
1078         return retval;
1079 }
1080
1081 static int stm32lx_lock_program_memory(struct flash_bank *bank)
1082 {
1083         struct target *target = bank->target;
1084         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1085         int retval;
1086         uint32_t reg32;
1087
1088         /* To lock the program memory, simply set the lock bit and lock PECR */
1089
1090         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1091                         &reg32);
1092         if (retval != ERROR_OK)
1093                 return retval;
1094
1095         reg32 |= FLASH_PECR__PRGLOCK;
1096         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1097                         reg32);
1098         if (retval != ERROR_OK)
1099                 return retval;
1100
1101         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1102                         &reg32);
1103         if (retval != ERROR_OK)
1104                 return retval;
1105
1106         reg32 |= FLASH_PECR__PELOCK;
1107         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1108                         reg32);
1109         if (retval != ERROR_OK)
1110                 return retval;
1111
1112         return ERROR_OK;
1113 }
1114
1115 static int stm32lx_erase_sector(struct flash_bank *bank, int sector)
1116 {
1117         struct target *target = bank->target;
1118         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1119         int retval;
1120         uint32_t reg32;
1121
1122         /*
1123          * To erase a sector (i.e. stm32lx_info->part_info.pages_per_sector pages),
1124          * first unlock the memory, loop over the pages of this sector
1125          * and write 0x0 to its first word.
1126          */
1127
1128         retval = stm32lx_unlock_program_memory(bank);
1129         if (retval != ERROR_OK)
1130                 return retval;
1131
1132         for (int page = 0; page < (int)stm32lx_info->part_info->pages_per_sector;
1133                         page++) {
1134                 reg32 = FLASH_PECR__PROG | FLASH_PECR__ERASE;
1135                 retval = target_write_u32(target,
1136                                 stm32lx_info->flash_base + FLASH_PECR, reg32);
1137                 if (retval != ERROR_OK)
1138                         return retval;
1139
1140                 retval = stm32lx_wait_until_bsy_clear(bank);
1141                 if (retval != ERROR_OK)
1142                         return retval;
1143
1144                 uint32_t addr = bank->base + bank->sectors[sector].offset + (page
1145                                 * stm32lx_info->part_info->page_size);
1146                 retval = target_write_u32(target, addr, 0x0);
1147                 if (retval != ERROR_OK)
1148                         return retval;
1149
1150                 retval = stm32lx_wait_until_bsy_clear(bank);
1151                 if (retval != ERROR_OK)
1152                         return retval;
1153         }
1154
1155         retval = stm32lx_lock_program_memory(bank);
1156         if (retval != ERROR_OK)
1157                 return retval;
1158
1159         return ERROR_OK;
1160 }
1161
1162 static inline int stm32lx_get_flash_status(struct flash_bank *bank, uint32_t *status)
1163 {
1164         struct target *target = bank->target;
1165         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1166
1167         return target_read_u32(target, stm32lx_info->flash_base + FLASH_SR, status);
1168 }
1169
1170 static int stm32lx_wait_until_bsy_clear(struct flash_bank *bank)
1171 {
1172         return stm32lx_wait_until_bsy_clear_timeout(bank, 100);
1173 }
1174
1175 static int stm32lx_unlock_options_bytes(struct flash_bank *bank)
1176 {
1177         struct target *target = bank->target;
1178         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1179         int retval;
1180         uint32_t reg32;
1181
1182         /*
1183         * Unlocking the options bytes is done by unlocking the PECR,
1184         * then by writing the 2 FLASH_PEKEYR to the FLASH_OPTKEYR register
1185         */
1186
1187         /* check flash is not already unlocked */
1188         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR, &reg32);
1189         if (retval != ERROR_OK)
1190                 return retval;
1191
1192         if ((reg32 & FLASH_PECR__OPTLOCK) == 0)
1193                 return ERROR_OK;
1194
1195         if ((reg32 & FLASH_PECR__PELOCK) != 0) {
1196
1197                 retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR, PEKEY1);
1198                 if (retval != ERROR_OK)
1199                         return retval;
1200
1201                 retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PEKEYR, PEKEY2);
1202                 if (retval != ERROR_OK)
1203                         return retval;
1204         }
1205
1206         /* To unlock the PECR write the 2 OPTKEY to the FLASH_OPTKEYR register */
1207         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_OPTKEYR, OPTKEY1);
1208         if (retval != ERROR_OK)
1209                 return retval;
1210
1211         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_OPTKEYR, OPTKEY2);
1212         if (retval != ERROR_OK)
1213                 return retval;
1214
1215         return ERROR_OK;
1216 }
1217
1218 static int stm32lx_wait_until_bsy_clear_timeout(struct flash_bank *bank, int timeout)
1219 {
1220         struct target *target = bank->target;
1221         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1222         uint32_t status;
1223         int retval = ERROR_OK;
1224
1225         /* wait for busy to clear */
1226         for (;;) {
1227                 retval = stm32lx_get_flash_status(bank, &status);
1228                 if (retval != ERROR_OK)
1229                         return retval;
1230
1231                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
1232                 if ((status & FLASH_SR__BSY) == 0)
1233                         break;
1234
1235                 if (timeout-- <= 0) {
1236                         LOG_ERROR("timed out waiting for flash");
1237                         return ERROR_FAIL;
1238                 }
1239                 alive_sleep(1);
1240         }
1241
1242         if (status & FLASH_SR__WRPERR) {
1243                 LOG_ERROR("access denied / write protected");
1244                 retval = ERROR_FAIL;
1245         }
1246
1247         if (status & FLASH_SR__PGAERR) {
1248                 LOG_ERROR("invalid program address");
1249                 retval = ERROR_FAIL;
1250         }
1251
1252         /* Clear but report errors */
1253         if (status & FLASH_SR__OPTVERR) {
1254                 /* If this operation fails, we ignore it and report the original retval */
1255                 target_write_u32(target, stm32lx_info->flash_base + FLASH_SR, status & FLASH_SR__OPTVERR);
1256         }
1257
1258         return retval;
1259 }
1260
1261 static int stm32lx_obl_launch(struct flash_bank *bank)
1262 {
1263         struct target *target = bank->target;
1264         struct stm32lx_flash_bank *stm32lx_info = bank->driver_priv;
1265         int retval;
1266
1267         /* This will fail as the target gets immediately rebooted */
1268         target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR,
1269                          FLASH_PECR__OBL_LAUNCH);
1270
1271         size_t tries = 10;
1272         do {
1273                 target_halt(target);
1274                 retval = target_poll(target);
1275         } while (--tries > 0 &&
1276                  (retval != ERROR_OK || target->state != TARGET_HALTED));
1277
1278         return tries ? ERROR_OK : ERROR_FAIL;
1279 }
1280
1281 static int stm32lx_mass_erase(struct flash_bank *bank)
1282 {
1283         int retval;
1284         struct target *target = bank->target;
1285         struct stm32lx_flash_bank *stm32lx_info = NULL;
1286         uint32_t reg32;
1287
1288         if (target->state != TARGET_HALTED) {
1289                 LOG_ERROR("Target not halted");
1290                 return ERROR_TARGET_NOT_HALTED;
1291         }
1292
1293         stm32lx_info = bank->driver_priv;
1294
1295         retval = stm32lx_unlock_options_bytes(bank);
1296         if (retval != ERROR_OK)
1297                 return retval;
1298
1299         /* mass erase flash memory */
1300         /* set the RDP protection level to 1 */
1301         retval = target_write_u32(target, OPTION_BYTES_ADDRESS, OPTION_BYTE_0_PR1);
1302         if (retval != ERROR_OK)
1303                 return retval;
1304
1305         retval = stm32lx_obl_launch(bank);
1306         if (retval != ERROR_OK)
1307                 return retval;
1308
1309         retval = stm32lx_unlock_options_bytes(bank);
1310         if (retval != ERROR_OK)
1311                 return retval;
1312
1313         /* set the RDP protection level to 0 */
1314         retval = target_write_u32(target, OPTION_BYTES_ADDRESS, OPTION_BYTE_0_PR0);
1315         if (retval != ERROR_OK)
1316                 return retval;
1317
1318         retval = stm32lx_wait_until_bsy_clear_timeout(bank, 30000);
1319         if (retval != ERROR_OK)
1320                 return retval;
1321
1322         retval = stm32lx_obl_launch(bank);
1323         if (retval != ERROR_OK)
1324                 return retval;
1325
1326         retval = target_read_u32(target, stm32lx_info->flash_base + FLASH_PECR, &reg32);
1327         if (retval != ERROR_OK)
1328                 return retval;
1329
1330         retval = target_write_u32(target, stm32lx_info->flash_base + FLASH_PECR, reg32 | FLASH_PECR__OPTLOCK);
1331         if (retval != ERROR_OK)
1332                 return retval;
1333
1334         return ERROR_OK;
1335 }