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