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