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