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