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