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