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